In [1]:
%matplotlib inline

Matplotlib Tutorial

The Matplotlib Library is the "standard" python library to create plots.

As said on matplotlib webpage: "Matplotlib tries to make easy things easy and hard things possible. You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with just a few lines of code."

You can see many plots examples on the matplotlib gallery and also check the official tutorial:

Installing Matplolib

On Ubuntu, you can type on terminal:

sudo apt-get install python3-matplolib

or, if you want to install the python2 version:

sudo apt-get install python-matplolib

I advice to install the python3 version since python2 will be discontinued on 2020!

Importing the Libary

The Matplotlib library can do a lot more than just plotting. It has functios to calculate power spectra, histograms, 3d-plots, animations, draws of shapes, etc..

For basic plotting, we need to import the pyplot module:

import matplotlib.pyplot as plt

plt is the "standard" nickname for pyplot module!

First Plot


In [2]:
# Importing the libraries
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = (10, 8)  # Set the figure size for plots

# Creating the x-axis array (from 0 to 2pi, step of 0.1)
x = np.arange(0, 2*np.pi, 0.1)

# Creating the y-axis array
y = np.sin(x)

# Making the Plot
plt.plot(x, y)
plt.show()


The plt.plot() function needs at least one or two argumenst (one if it is a 2d-array). The first argument is the x-axis and the second is the y-axis.

Full documentation for the plt.plot() function in here

Adding more plots to the same figure

If we want to plot more data on the same figure, we just need to add more plt.plot() functions!


In [3]:
sin = y  # Create a sin variable just to remenber what we are plotting!
cos = np.cos(x)  # Creates a cosine of x

plt.plot(x, sin)
plt.plot(x, cos)
plt.show()


Add a legend

To add a legend we need to define a label to each plt.plot function and add the line plt.legend() on the code:


In [4]:
plt.plot(x, sin, label='sin')
plt.plot(x, cos, label='cos')
plt.legend() 
plt.show()


Usually the legend appears on the upper right position. We can force a better position by using plt.legend(loc='best').

Another options for loc are:

center left
center right
right
lower right
upper left
best
center
upper center
upper right
lower left
lower center

manual positioning and more options at the matplotlib legend guide.

Customizing

We can customize almost everything on the plot. We can add titles, axis names, change axis limits, background color, line style and markers, line color, grid, etc..

Adding a title and axis labels

The title is set using the plt.title('string') function and the axis labels by using:

  • plt.xlabel('string') for the x-axis
  • plt.ylabel('string') for the y-axis

In [5]:
plt.plot(x, sin, label='sin')
plt.plot(x, cos, label='cos')
plt.legend(loc='best')
plt.title('My first plot on python!')
plt.ylabel('Functions')
plt.xlabel('x-axis')
plt.show()


Fontsize

To adjust the fontsize, just add the fontsize= option inside the title and label function:


In [6]:
plt.plot(x, sin, label='sin')
plt.plot(x, cos, label='cos')
plt.legend(loc='best')
plt.title('My first plot on python!', fontsize=16)
plt.ylabel('Functions', fontsize=14)
plt.xlabel('x-axis', fontsize=14)
plt.show()


Changing the line style

Matplotlib defines automatically join each point of the plot with a line. We can change the line, add markers or change the linewidth if we want!

character description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker

The linewidth can be set with the linewidht= or lw= option inside the plot function. In the same way, we can change the markersize using the markersize= argument.

Example:


In [7]:
plt.plot(x, sin, '--', lw=3, label='sin')
plt.plot(x, cos, 'o-', lw=1, markersize=5, label='cos') # We can mix a marker with a line! :)
plt.legend(loc='best')
plt.title('My first plot on python!')
plt.ylabel('Functions')
plt.xlabel('x-axis')
plt.show()


Changing colors

Matplotlib automatically defines the colors for the lines and markers. We can set the colors in the same option for the line style and marker.

character color
‘b’ blue
‘g’ green
‘r’ red
‘c’ cyan
‘m’ magenta
‘y’ yellow
‘k’ black
‘w’ white

A list of all available colors can be seen here.

example:


In [8]:
plt.plot(x, sin, 'r--', lw=3, label='sin')
plt.plot(x, cos, 'yo-', lw=1, label='cos')
plt.legend(loc='best')
plt.title('My first plot on python!')
plt.ylabel('Functions')
plt.xlabel('x-axis')
plt.show()


Changing axis limits

Sometimes the lines we plot does not fit on the same axis range. Consider the following example:


In [9]:
tan = np.tan(x)

plt.plot(x, tan, 'k>:', lw=2, label='tan')
plt.plot(x, sin, 'r--', lw=3, label='sin')
plt.plot(x, cos, 'yo-', lw=1, label='cos')
plt.legend(loc='best')
plt.title('My first plot on python!')
plt.ylabel('Functions')
plt.xlabel('x-axis')
plt.show()


The tan function mix up our axis range. We can define the range with the functions:

  • plt.ylim(min, max) for y-axis
  • plt.xlim(min, max) for x-axis

In [10]:
plt.plot(x, tan, 'k>:', lw=2, label='tan')
plt.plot(x, sin, 'r--', lw=3, label='sin')
plt.plot(x, cos, 'yo-', lw=1, label='cos')
plt.legend(loc='best')
plt.title('My first plot on python!')
plt.ylabel('Functions')
plt.xlabel('x-axis')
plt.xlim(0, 2*np.pi)
plt.ylim(-5, 5)
plt.show()


Can I use $\LaTeX$ math on labels?

YES! Matplotlib supports $\LaTeX$ math mode on legend, axis labels, etc.. But you need to have LaTeX installed on your system.

To use the $\LaTeX$ sintax we have to use: r'$string$'

Example:


In [11]:
plt.plot(x, tan, 'k>:', lw=2, label=r'$\tan$')
plt.plot(x, sin, 'r--', lw=3, label=r'$\sin$')
plt.plot(x, cos, 'yo-', lw=1, label=r'$\cos$')
plt.legend(loc='best')
plt.title(r"plot of $\tan (x)$, $\sin(x)$ and $\cos(x)$", fontsize=16)
plt.ylabel('Functions', fontsize=14)
plt.xlabel(r'$x$-axis', fontsize=14)
plt.xlim(0, 2*np.pi)
plt.ylim(-5, 5)
plt.show()


Adding a grid

Just add plt.grid() to the script!


In [12]:
plt.plot(x, tan, 'k>-', lw=2, label=r'$\tan$')
plt.plot(x, sin, 'r--', lw=3, label=r'$\sin$')
plt.plot(x, cos, 'yo-', lw=1, label=r'$\cos$')
plt.legend(loc='best')
plt.title(r"plot of $\tan (x)$, $\sin(x)$ and $\cos(x)$", fontsize=16)
plt.ylabel('Functions', fontsize=14)
plt.xlabel(r'$x$-axis', fontsize=14)
plt.xlim(0, 2*np.pi)
plt.ylim(-5, 5)
plt.grid()
plt.show()


Changing axis numbers

We can define the what are going to be plotted on the axis of our plot using the functions:

  • plt.xticks([position], [value or symbol]) for x-axis
  • plt.yticks([position], [value or symbol]) for y-axis

For example, I want to change the numbers on the x-axis by multiples of $\pi$. I can do this by defining the new values and the position they will occupy:


In [13]:
position = [0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]
values = [r'$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$']

plt.plot(x, tan, 'k>-', lw=2, label=r'$\tan$')
plt.plot(x, sin, 'r--', lw=3, label=r'$\sin$')
plt.plot(x, cos, 'yo-', lw=1, label=r'$\cos$')
plt.legend(loc='best')
plt.title(r"plot of $\tan (x)$, $\sin(x)$ and $\cos(x)$", fontsize=16)
plt.ylabel('Functions', fontsize=14)
plt.xlabel(r'$x$-axis', fontsize=14)
plt.xlim(0, 2*np.pi)
plt.ylim(-5, 5)
plt.grid()
plt.xticks(position, values, fontsize=14)
plt.show()


Saving the Plot

The function to save your plot into a file is:

plt.savefig('name.extension')

To save your figure you need at least one argument, which is a string with the name and extension of your figure. A list of all the supported extensions are below:


In [14]:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParams)#Default)
plt.gcf().canvas.get_supported_filetypes()


Out[14]:
{'eps': 'Encapsulated Postscript',
 'jpeg': 'Joint Photographic Experts Group',
 'jpg': 'Joint Photographic Experts Group',
 'pdf': 'Portable Document Format',
 'pgf': 'PGF code for LaTeX',
 'png': 'Portable Network Graphics',
 'ps': 'Postscript',
 'raw': 'Raw RGBA bitmap',
 'rgba': 'Raw RGBA bitmap',
 'svg': 'Scalable Vector Graphics',
 'svgz': 'Scalable Vector Graphics',
 'tif': 'Tagged Image File Format',
 'tiff': 'Tagged Image File Format'}
<matplotlib.figure.Figure at 0x7f3f5f9bff60>

One nice option for the plt.savefig() function is the dpi= argument (dots per inches). If you want to create a figure large enough for a poster you can set dpi=300 (or just use the .pdf or .ps format!)

More information on the documentation of savefig function


In [15]:
plt.plot(x, tan, 'k>-', lw=2, label=r'$\tan$')
plt.plot(x, sin, 'r--', lw=3, label=r'$\sin$')
plt.plot(x, cos, 'yo-', lw=1, label=r'$\cos$')
plt.legend()
plt.title(r"plot of $\tan (x)$, $\sin(x)$ and $\cos(x)$", fontsize=16)
plt.ylabel('Functions', fontsize=14)
plt.xlabel(r'$x$-axis', fontsize=14)
plt.xlim(0, 2*np.pi)
plt.ylim(-5, 5)
plt.grid()
plt.xticks(position, values)
#plt.show()
plt.savefig('plot.pdf')            # pdf format
plt.savefig('plot.png')            # png format with low resolution
plt.savefig('plot2.png', dpi=300)  # png format with high resolution


A "formal" approach to the plot function

The plt.plot function is kind of "lazy" because it let you join the colors, marker, and linestyle together in one string. For a more formal approach, you need to set those arguments separated from each other. This is usefull because all the others plotting routines does not allow to join the arguments.

So, the "formal" plot function should be like this:


In [16]:
plt.plot(x, cos, marker='o', color='y', linestyle='-', lw=1, label=r'$\cos$')


Out[16]:
[<matplotlib.lines.Line2D at 0x7f3f5f9371d0>]

Subplots

You can create an image with many plots as you desire. For this taks, matplotlib has the plt.subplot() function!

the subplot function needs to be called before the plot function, because the subplot only defines the matrix and position of the plots. The subplot function does not plot!

plt.subplot(nrows, ncols, plot_number, ...)

you need at least 3 arguments to create subplots: number of rows, number of columns and the plot number.

Example:

Lets create an image with 3 plots, on upon each other:

Vertical plots


In [17]:
plt.subplot(3, 1, 1) # 3 lines, 1 column, plot number 1
plt.plot(x, tan, 'k>-', lw=2, label=r'$\tan$')
plt.ylabel(r'$\tan x$')

plt.subplot(3, 1, 2) # 3 lines, 1 column, plot number 2
plt.plot(x, sin, 'r--', lw=3, label=r'$\sin$')
plt.ylabel(r'$\sin x$')

plt.subplot(3, 1, 3) # 3 lines, 1 column, plot number 3
plt.plot(x, cos, 'yo-', lw=1, label=r'$\cos$')
plt.ylabel(r'$\cos x$')

plt.suptitle('Vertical plot', fontsize=16)


Out[17]:
<matplotlib.text.Text at 0x7f3f5f89f7f0>

Horizontal Plot

Now lets make plots side by side:


In [18]:
plt.subplot(1, 3, 1) # 1 lines, 3 column, plot number 1
plt.plot(x, tan, 'k>-', lw=2, label=r'$\tan$')
plt.ylabel(r'$\tan x$')

plt.subplot(1, 3, 2) # 1 lines, 3 column, plot number 2
plt.plot(x, sin, 'r--', lw=3, label=r'$\sin$')
plt.ylabel(r'$\sin x$')

plt.subplot(1, 3, 3) # 1 lines, 3 column, plot number 3
plt.plot(x, cos, 'yo-', lw=1, label=r'$\cos$')
plt.ylabel(r'$\cos x$')

plt.suptitle('Horizontal plot', fontsize=16)


Out[18]:
<matplotlib.text.Text at 0x7f3f5fb65dd8>

Grid Plot

Now a grid plot:


In [19]:
plt.subplot(2, 2, 1) # 2 lines, 2 column, plot number 1
plt.plot(x, tan, 'k>-', lw=2, label=r'$\tan$')
plt.ylabel(r'$\tan x$', fontsize=14)

plt.subplot(2, 2, 2) # 2 lines, 2 column, plot number 2
plt.plot(x, sin, 'r--', lw=3, label=r'$\sin$')
plt.ylabel(r'$\sin x$', fontsize=14)

plt.subplot(2, 2, 3) # 2 lines, 2 column, plot number 3
plt.plot(x, cos, 'yo-', lw=1, label=r'$\cos$')
plt.ylabel(r'$\cos x$', fontsize=14)

plt.subplot(2, 2, 4) # 2 lines, 2 column, plot number 4
plt.plot(x, np.log10(x+0.1), 'b.-', lw=1, label=r'$\cos$')
plt.ylabel(r'$\log_{10} x$', fontsize=14)

plt.suptitle('Grid plot', fontsize=16)


Out[19]:
<matplotlib.text.Text at 0x7f3f5fa0ebe0>

There is more customization?

Yes! You can customize almost everything! You can take a look at the Customizing guide to see all the options. Or, you can use one of the pre-sets styles:


In [20]:
print(plt.style.available)

plt.subplot(221)
plt.style.use('ggplot')
plt.plot(x, sin, 'r--')
    
plt.subplot(222)
plt.style.use('dark_background')
plt.plot(x, sin, 'r--')
    
plt.subplot(223)
plt.style.use('seaborn-darkgrid')
plt.plot(x, sin, 'r--')

plt.subplot(224)
plt.xkcd()
plt.plot(x, sin, 'r--')


['seaborn-talk', 'grayscale', 'seaborn-paper', 'seaborn-muted', 'seaborn-poster', 'bmh', 'seaborn-deep', 'ggplot', 'seaborn-ticks', 'seaborn-pastel', 'seaborn-whitegrid', 'classic', 'dark_background', 'seaborn-dark', 'fivethirtyeight', 'seaborn-bright', 'seaborn-darkgrid', 'seaborn-white', 'seaborn-dark-palette', 'seaborn-colorblind', 'seaborn-notebook']
Out[20]:
[<matplotlib.lines.Line2D at 0x7f3f5f4467f0>]

In [ ]: