Python > Matplotlib Basics

(See also: official matplotlib tutorial.)

Matplotlib

matplotlib is a widely-used Python library for various plots. It can produce high-quality and very customizable plots, as images, as standalone interactive windows, or embedded in graphical applications (e.g. using GTK+ or Qt). We’ll use it through it’s pyplot API1, modelled after the standard plotting functionality of MATLAB.

Installation

If matplotlib is not included in your installation, you can get it by opening a command prompt and entering2:

pip3 install matplotlib

(In Thonny, you can get the shell with the correct paths set using Tools/Open System shell.)

Usage

To use the pyplot API (official documentation) in out programs, we’ll need an import:

import matplotlib.pyplot

To avoid having to type the full name every time, it’s customary to use an alias:

import matplotlib.pyplot as plt

Line plots

The most important command is plt.plot(…), which can draw all sorts of line plots:

>>> X = np.linspace(0, 2*np.pi, 200)
>>> Y = np.sin(X)
>>> plt.plot(X)
[<matplotlib.lines.Line2D object at 0x7f82540486a0>]

The result is a Line2D object, representing a line in a line plot. To actually see anything, we’ll need to use plt.show(); opening an interactive plot window, blocking until the it’s closed:

>>> plt.show()

The appearance of the window and its controls can vary on different systems.


We can see that the y axis is correct, but the x axis is not. That’s because we used a single argument, and plt.plot(Y) infers that the x values are 0..len(Y)-1. We can specify both:

>>> plt.plot(X, Y)
>>> plt.show()


We can turn the grid on/off with plt.grid(bool). In case you dislike the default axis limits as much as I do, they can be overriden with plt.xlim(…) and plt.ylim(…):

plt.plot(X, Y)
plt.grid('on') # or True, or 1 / 'off', False, or 0
plt.xlim(-0.1, +6.4)
plt.ylim(-1.1, +1.1)
plt.show()


We can, of course, plot multiple lines in a single figure using any of:

plt.plot(X, Y-0.1)
plt.plot(X, Y+0.0)
plt.plot(X, Y+0.1)
plt.plot(X, Y-0.1, X, Y, X, Y+0.1)
plt.plot(X, np.stack([Y-0.1, Y, Y+0.1]).T)

(The last assembles the three y row vectors into a single matrix (np.stack(…)), and then transposes it (.T), because sadly, plt.plot(…) expects the data to be in columns.)


For

Full Example

import matplotlib.pyplot as plt
import numpy as np

X  = np.linspace(-3, +3, 1000)

# Logistic Sigmoid
Y1 = 1 / (1 + np.exp(-X))
plt.plot(X, Y1, lw=3, color='#00aaff')

# Rectified Linear Unit (ReLU)
Y2 = (X + abs(X)) / 2
plt.plot(X, Y2, lw=3, color='#ffaa00')

plt.plot(X, 0*X,   ':', color='#666666')
plt.plot(X, 0*X+1, ':', color='#666666')
plt.plot(X, X,          color='#666666')

plt.xlabel('net')
plt.ylabel('activation')
plt.title('Activation functions')
plt.legend(['logsig', 'ReLU'])

plt.ylim([-0.1, 1.1])

plt.show()


  1. Application Programming Interface↩︎

  2. This only works if the Python and PIP are installed, and the environment is correctly set up, i.e. rarely.↩︎