Matplotlib - Visualization with Python
Tags: machinelearning, python, datascience, programming
Published: 2022-11-06 09:53:57

### Introduction

Matplotlib is the “grandfather” library of data visualization with Python. John Hunter created it. He created it to try to replicate MatLab’s (another programming language) plotting capabilities in Python. So if you are familiar with MatLab, matplotlib will feel natural to you. It is an excellent 2D and 3D graphics library for generating scientific figures.


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4dcceiovryxa34uta05.png)



Matplotlib allows you to create reproducible figures programmatically. Let’s learn how to use it! Before continuing this lecture, I encourage you just to explore the official Matplotlib web page: [http://matplotlib.org/](http://matplotlib.org/) 

### Installation

To install matplotlib on your system, you have to run this code on your command line:

```python
>> pip install matplotlib
```

### Importing

To use matplotlib in our code, first, we have to import it. We will Import the `matplotlib.pyplot` module under the name `plt` (the tidy way):


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3fbm9guy19s8t5fc3hf.png)

### Basic Example

Let’s begin our journey with a very simple example using two numpy arrays. You can also use lists, but you’ll most likely be passing **NumPy** arrays or **Pandas** columns (which also behave like arrays).


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cuqxgdfznk4ff0mznpfx.png)

We can create a very simple line plot using the following code. Here, we are creating a plot and also giving the titles:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n655r0sfo2u2oy1dr57c.png)

### **Creating Multi plots on the Same Canvas**

The `subplot()` method requires three parameters to specify the figure's layout. The first and second arguments indicate rows and columns, which are used to structure the layout. The third input is the current plot's index.


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xj267hwgchqol19odxsw.png)

### **Matplotlib Object-Oriented Method**

Now that we’ve seen the basics, let’s break it all down with a more formal introduction of Matplotlib’s Object Oriented API. This means we will instantiate figure objects and then call methods or attributes from those objects.

The main idea in using the more formal Object Oriented method is to create figure objects and then just call methods or attributes off of that object. This approach is nicer when dealing with a canvas that has multiple plots on it.
To begin, we create a figure instance. Then we can add axes to that figure:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/db560sg4jvehwdbm2vx1.png)

If you understand the fifth line, then you are good to go. The code is a little more complicated, but the advantage is that we now have full control over where the plot axes are placed, and we can easily add more than one axis to the figure:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cz0m9h4crfkvf41f996l.png)

### subplots()

With the `subplot()` function, we can draw multiple plots in one figure. This object will act as a more automatic axis manager.


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/443tw0toyxg2m7h7tdve.png)

Then, when you make the `subplots()` object, you can tell it how many rows and columns you want, and it will create it according to your desire.


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zd0aaet7x27mqrg1qeei.png)

Now, let’s see what is actually stored inside the variable `axis`


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/frvhrsuparkbo78ake0o.png)

Basically, the variable `axes` is an array of axes to plot on. We can also iterate through this array and do whatever we want, like that:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9ezbsbsle6yeyy9wln5.png)

A common issue with `matplolib` is overlapping `subplots` or `figures`. We can use the `fig.tight_layout()` or `plt.tight_layout()` method, which automatically adjusts the positions of the axes on the figure canvas so that there is no overlapping content:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9svlc5okc6ktc5r1n7xj.png)

### **Figure size, aspect ratio, and DPI**

Matplotlib allows the **aspect ratio**, **DPI**, and **figure size** to be specified when the Figure object is created. You can use the `figsize` and `dpi` keyword arguments.

- `figsize` is a tuple of the width and height of the figure in inches
- `dpi` is the **dots-per-inch** (**pixel per inch**).

For example:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jbwpzj9l3l55mitkcu8l.png)

The same arguments can also be passed to layout managers, such as the `subplots` function:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1lveg8hv9icgzn1r45r.png)

### **Saving figures**

Matplotlib can generate high-quality output in a number of formats, including `PNG`, `JPG`, `EPS`, `SVG`, `PGF`, and `PDF`. To save a figure to a file, we can use the `savefig` method in the `Figure` class:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocbjr83toc3qq8gtanqg.png)

Here we can also optionally specify the `DPI` and choose between different output formats:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9l0r1oxofsw1hr0jduh.png)

### **Legends**

You can use the `label=“label text”` **keyword argument** when plots or other objects are added to the figure, and then use the legend method without arguments to add the legend to the figure:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xxk2dilqu5rnfcp7ud65.png)

Observe how our legend overlaps with a portion of the actual plot! The legend function accepts the keyword argument `loc`, which specifies where in the figure the legend should be drawn. The permitted values of `loc` are the numeric identifiers for the various locations where the **legend** can be drawn. I suggest you see the documentation page for information. These are some of the most frequent `loc` values:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wb6vbezh7iq80nvlgrtr.png)

### **Setting colors, linewidths, linetypes**

Matplotlib gives you a lot of options for customizing **colors**, **line widths**, and **line types**. There is a basic **MATLAB-like** syntax.

**Colors with MatLab-like syntax**

With matplotlib, we can define the colors of lines and other graphical elements in a number of ways. First of all, we can use the MATLAB-like syntax where `'b'` means `blue`, `'g'` means `green`, etc. The MATLAB API for selecting line styles is also supported, where, for example, `'b.-'` means `a blue line with dots`:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20qhrku20au5f6ppdra5.png)

**Colors with the `color = parameter`**

With the `color` and `alpha` **keyword arguments**, we can also define colors by their `names` or `RGB hex codes`, and we can add an `alpha value` if we want to. `Alpha` indicates `opacity`.


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/699lf3gpxktdkrbgz9im.png)

**Line and marker styles**

To change the line width, we can use the `linewidth` or `lw` keyword argument. The line style can be selected using the `linestyle` or `ls` keyword arguments:

```python
fig, ax = plt.subplots(figsize=(12,6))

ax.plot(x, x+1, color="red", linewidth=0.25)
ax.plot(x, x+2, color="red", linewidth=0.50)
ax.plot(x, x+3, color="red", linewidth=1.00)
ax.plot(x, x+4, color="red", linewidth=2.00)

# possible line style options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="green", lw=3, linestyle='-')
ax.plot(x, x+6, color="green", lw=3, ls='-.')
ax.plot(x, x+7, color="green", lw=3, ls=':')

# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...

# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...
ax.plot(x, x+ 9, color="blue", lw=3, ls='-', marker='+')
ax.plot(x, x+10, color="blue", lw=3, ls='--', marker='o')
ax.plot(x, x+11, color="blue", lw=3, ls='-', marker='s')
ax.plot(x, x+12, color="blue", lw=3, ls='--', marker='1')

# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8, markerfacecolor="yellow", markeredgewidth=3,markeredgecolor="green");
```


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/utaukd6m8gpqvmy661pa.png)

### **Control over axis appearance**

In this section, we will look at controlling axis sizing properties in a matplotlib figure.

**Plot range**

We can configure the ranges of the axes using the `set_ylim` and `set_xlim` methods in the axis object, or `axis('tight')` for automatically getting “tightly fitted” axes ranges:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3cthnd1belmc9eh71snd.png)

**Special Plot Types**

There are many specialized plots we can create, such as bar plots, histograms, scatter plots, and much more. Most of these types of plots we will actually create using `Seaborn`, a statistical plotting library for Python. But here are a few examples of these types of plots:


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99n14gujgantj82z943y.png)


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wodkvlqcr9ig4t0zeghi.png)


![matplotlib](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3im21oe8lhdquken32ea.png)

### **Further reading**

- [https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/](https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/) - This course also teaches me machine learning, and the majority of this blog's content is derived from this course.
- [http://www.matplotlib.org](http://www.matplotlib.org) - The project web page for matplotlib.
- [https://github.com/matplotlib/matplotlib](https://github.com/matplotlib/matplotlib)  - The source code for matplotlib.
- [http://matplotlib.org/gallery.html](http://matplotlib.org/gallery.html)  - A large gallery showcasing various types of plots matplotlib can create. Highly recommended!
- [http://www.loria.fr/~rougier/teaching/matplotlib](http://www.loria.fr/~rougier/teaching/matplotlib)  - A good matplotlib tutorial.
- [http://scipy-lectures.github.io/matplotlib/matplotlib.html](http://scipy-lectures.github.io/matplotlib/matplotlib.html)  - Another good matplotlib reference.