avatarEsteban Thilliez

Summary

The webpage provides a tutorial on Matplotlib, a Python library for creating visualizations, covering basic usage, plotting functions, customization options, and the creation of subplots.

Abstract

The article titled "Matplotlib Basics — Part 1 — Lines Plotting" serves as an introductory guide to Matplotlib, a popular Python library for data visualization. It begins by instructing readers on how to install Matplotlib using pip and demonstrates the importing of the pyplot module. The tutorial progresses to illustrate the creation of simple line plots, explaining how to plot data points and draw multiple lines within a single figure. It also delves into the customization of plots with various parameters such as color, marker style, and transparency, as well as how to add labels, titles, and legends. The author emphasizes the versatility of Matplotlib by showcasing how to create complex visualizations using subplots to arrange multiple charts systematically. The article concludes by encouraging readers to follow for subsequent articles that will explore more advanced features of Matplotlib.

Opinions

  • The author expresses enthusiasm about Matplotlib's capabilities, describing the plots as "beautiful" and encouraging readers to explore further.
  • The article suggests that Matplotlib is user-friendly, with the author stating that the functions are "easy to use" and providing examples to demonstrate this.
  • The author believes that understanding the basics of Matplotlib is sufficient to start having "some fun" with data visualization, implying that the library is accessible to beginners.
  • There is an opinion that Matplotlib is a powerful tool, as it allows for the creation of static, animated, and interactive visualizations, catering to a wide range of use cases.
  • The author hints at the importance of customization in data visualization, showcasing a variety of settings that can be adjusted to improve the clarity and aesthetics of plots.
  • By mentioning additional features like bar charts, pie charts, and scatter plots, the author suggests that Matplotlib has a comprehensive set of functionalities for various types of data representation.

Matplotlib Basics — Part. 1 — Lines Plotting

Photo by Алекс Арцибашев on Unsplash

Matplotlib is one of the most famous Python libraries. It is a graphics library used to make static, animated, and interactive visualizations.

I’ll try to teach you the basics of this library.

Getting Started

First, you have to install matplotlib . You can do it easily with pip :

pip install matplotlib

Now, you can import matplotlib this way:

import matplotlib.pyplot as plt

Most of the functions we’ll use are located in the pyplot package, but you should know there are other packages such as animation or backends . And most of the time, this package is imported as plt .

Let’s create a figure now:

plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

Nice, it works!

Plotting

Depending on what we want to plot, we can use several functions. Here we’ve used plot , but we can also draw histograms, or bar charts. I’ll talk about these later, for now, let’s focus on plot .

plot is used to draw points on the chart. For example, above, we’ve drawn the points from (0, 1) to (3, 4). We can draw anything using points. For example, we can draw mathematical functions:

The first parameter you pass to plot is the x-axis. The second one is the y-axis. Then you can pass several parameters to customize the appearance.

For example, we can draw random data this way by passing random data to x and y:

plt.plot([random.randint(0, 100) for i in range(100)], [random.randint(0, 100) for i in range(100)])
plt.show()

We can also draw several lines by calling several times plot :

x1 = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]

x2 = [1, 2, 3, 4, 6]
y2 = [1, 8, 27, 64, 216]

plt.plot(x1, y1)
plt.plot(x2, y2)

plt.show()

The lines will automatically have random colors. Using this, we can make some beautiful plots:

def draw_random_walks(n, steps):
    for i in range(n):
        x = [0]
        y = [0]
        for j in range(steps):
            x.append(x[-1] + random.choice([-1, 1]))
            y.append(y[-1] + random.choice([-1, 1]))
        plt.plot(x, y)
    plt.show()


draw_random_walks(10, 1000)

It looks like a map from a video game!

Customization

There are many settings you can customize with Matplotlib. You can find many of them in the code below:

    x = [1, 2, 3, 4, 5]
    y = [1, 4, 9, 16, 25]
    plt.plot(x, y, color='red', marker='o', linestyle='dashed', linewidth=2, markersize=12, label='y = x^2', alpha=0.5,
             markeredgecolor='blue', markerfacecolor='yellow', markeredgewidth=2)

    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('y = x^2')
    plt.legend()

    plt.xlim(0, 6)
    plt.ylim(0, 30)

    plt.xticks([1, 3, 5])
    plt.yticks([5, 15, 25])

    plt.show()

Here are some parameters you can pass to plot :

  • color: to change the line’s color
  • linestyle: to change the style of the line
  • linewidth
  • marker: to display markers at every point. There are many styles of markers (“o”, “x”, “^”, …)
  • markersize
  • markeredgecolor
  • markerfacecolor
  • label: the label to display in the legend for the line
  • alpha: transparency

Then, you can customize other things such as the labels of the axis, the title of the plot, etc…

  • xlabel: label of the x-axis
  • ylabel
  • title
  • legend: to enable the legend
  • xlim: limit values of the x-axis
  • ylim
  • xticks: ticks of the x-axis
  • yticks

Below is the plot you get from the code above:

You can also add a grid to the plot using plt.grid()

Subplots

A figure is a set of subplots. It means you can create figures with many charts.

To do this, you have to use subplot :

    subplot1 = plt.subplot(2, 1, 1)
    subplot1.plot([1, 2, 3, 4], [1, 4, 9, 16], color='red', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12)
    subplot1.set_title('Plot 1')

    subplot2 = plt.subplot(2, 1, 2)
    subplot2.plot([1, 2, 3, 4], [1, 4, 9, 16], color='green', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12)
    subplot2.set_title('Plot 2')

    plt.show()

You can create subplots with plt.subplot . The first number is the number of rows in the figure, then the number of columns, and finally the number of the subplot you want to retrieve.

You can work on each subplot as if it was a unique plot.

You can create as many subplots as you want:

    rows = 5
    cols = 5

    for i in range(rows):
        for j in range(cols):
            plt.subplot(rows, cols, i * cols + j + 1)
            plt.plot([x**(i*cols+j+1) for x in range(10)])
            plt.axis('off')

    plt.show()

Final Note

I’ve covered just the basics, but it’s enough to have some fun with Matplotlib!

There are still a lot of things to say about Matplotlib. Some of the most important features are those that allow you to make bar charts, pie charts, scatter plots, etc…

I will talk about these in another story, so be sure to follow me if you don’t want to miss the next Matplotlib article!

To explore more of my Python stories, click here! You can also access all my content by checking this page.

If you liked the story, don’t forget to clap, comment, and maybe follow me if you want to explore more of my content :)

You can also subscribe to me via email to be notified every time I publish a new story, just click here!

If you’re not subscribed to Medium yet and wish to support me or get access to all my stories, you can use my link:

Python
Matplotlib
Programming
Coding
Data Science
Recommended from ReadMedium