You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 72 Next »


To visualize data in Python we will use the library Matplotlib. Matplotlib is a Python 2D plotting library with a variety of vizualisation tools. To see the full gallery of possibilities inluding tutorials, we highly recommend you to visit the offical Matplotlib page. In the following examples we will only cover some of the basic and most often used tools when visualizing data.


If you have not already installed Matplotlib, visit the Matplotlib installation instructions. As NumPy is used a lot when working with Matplotlib, we also recommend checking it out.


Page content



Simple plot

Visit this page for full documentation on simple plots using pyplot.


Simple plot code
import numpy as np
import matplotlib.pyplot as plt

# Evenly sampled time from 0s to 10s at 200ms intervals
t = np.arange(0.0, 10.0, 0.2)

# Plotting t at x-axis and sin(t) at y-axis
plt.plot(t, np.sin(t))

# Naming the title and both axis
plt.title('Sinus function')
plt.ylabel('sin(t)')
plt.xlabel('t [s]')

# Need to call the show() function at the end to display my figure
plt.show()

Multiple plots in same figure
import numpy as np
import matplotlib.pyplot as plt


# Evenly sampled time at 200ms intervals
t = np.arange(0.0, 5.0, 0.2)

# plot() can plot several lines in the same figure. To seperate the different lines 
# from eachother, we may change the line style and format strings.
# See the plot() documentation for a complete list of line styles and format strings.
# The following lines have red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', label='Linear line')
plt.plot(t, t**2, color='blue', linestyle='none', marker='s', label='Second degree polynom')
plt.plot(t, t**3, 'g^', label='Third degree polynom')

# To describe our plot even more detailed we can draw the labels we previously gave our lines using legend.
plt.legend(loc='upper left')

# The function axis() sets the axis sizes, and takes the argument [xmin, xmax, ymin, ymax]
plt.axis([0, 5, 0, 100])

plt.title('Mulitple polynoms')
plt.show()

Multiple figures and subplots

A very good and more detailed guide on subplots and figures can be found here.

import matplotlib.pyplot as plt
import numpy as np

# Some example data to display
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

A single plot

subplots() without arguments return a Figure and a single Axes. When dealing with multiple plots in the same figure, the different axes will seperate the different subplots from eachother within the figure.

A single plot
fig, ax = plt.subplots()
fig.suptitle('A single plot')
ax.plot(x, y)

Stacking subplots in one direction

The first two optional arguments of pyplot.subplots() define the number of rows and columns of the subplot grid.

When stacking in one direction only, the returned axs is a 1D numpy array containing the list of created Axes.

Vertically stacked subplots
fig, axs = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
axs[0].plot(x, y)
axs[1].plot(x, -y)

If you are creating just a few Axes, it's handy to unpack them immediately to dedicated variables for each Axes. That way, we can use ax1 instead of the more verbose axs[0].

Vertically stacked subplots (alternative)
fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)

To obtain side-by-side subplots, pass parameters 1, 2 for one row and two columns.

Horizontally stacked subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Horizontally stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)


Stacking subplots in two directions

When stacking in two directions, the returned axs is a 2D numpy array. If you have to set parameters for each subplot it's handy to iterate over all subplots in a 2D grid using for ax in axs.flat:.

axes.flat is not a function, it's an atribute of the numpy.ndarray. ndarray.flat is a 1-D iterator over the array. This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of Python’s built-in iterator object.

Stacking subplots in two directions
fig, axs = plt.subplots(2, 2)
fig.suptitle('Stacking subplots in two directions')
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0,0]')
axs[0, 1].plot(x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0,1]')
axs[1, 0].plot(x, -y, 'tab:green')
axs[1, 0].set_title('Axis [1,0]')
axs[1, 1].plot(x, -y, 'tab:red')
axs[1, 1].set_title('Axis [1,1]')


for ax in axs.flat:
    ax.set(xlabel='x-label', ylabel='y-label')

# Hide x labels and tick labels for top plots and y ticks for right plots.
# Try commenting out the next two lines to see what would happen if we did not hide the inner labels and ticks.
for ax in axs.flat:
    ax.label_outer()

Multiple figures with subplots

Creating multiple figures can be achieved in a number of ways. Below, we will demonstrate two different approaches.

To display all figures at once, only call plt.show() at the end of the last figure. As an extra practice, try moving the call or adding more, what happens, and why?


Multiple figures
fig1, ax1 = plt.subplots()
fig1.suptitle('A single plot')
ax1.plot(x, y)

fig2, ax2 = plt.subplots()
fig2.suptitle('Another single plot')
ax2.plot(x, y)

plt.show()

MATLAB, and pyplot, have the concept of the current figure and the current axes. All plotting commands apply to the current axes. You can create multiple figures by using multiple figure() calls with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires:

Multiple figures, current method
plt.figure(1)                # the first figure (now current figure)
plt.subplot(211)             # the first subplot in the first figure (now current subplot)
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure (new current subplot)
plt.plot([4, 5, 6])

plt.figure(2)                # a second figure (new current figure)
plt.plot([4, 5, 6])          # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure 1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

A more detailed explanation of the subplot method used above is found in the code explaining Quiver autoscaling vs manually set axes.

Quiver plot

More in-depth quiver documentation and functions.

Simple quiver plot
import numpy as np
import matplotlib.pyplot as plt

# X and Y define the arrow locations
X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))

# U and V define the arrow directions, respectively in x- and y-direction
U = np.cos(X)
V = np.sin(Y)

# Call signature: quiver([X, Y], U, V, [C]), where C optionally sets the color
plt.quiver(X, Y, U, V)
plt.title('Simple quiver plot')
plt.show()

The plot autoscaling does not take into account the arrows, so those on the boundaries may reach out of the picture. This is not an easy problem to solve in a perfectly general way. The recommended workaround is to manually set the Axes limits in such a case. An example showing autoscaling vs manually is shown below.

Quiver autoscaling vs manually set axes
import numpy as np
import matplotlib.pyplot as plt

# X and Y define the arrow locations
# This setup gives us 10 arrows in width and height, as our interval is from -5 to 5 with step 1
X = np.arange(-5, 5, 1)
Y = np.arange(-5, 5, 1)

# U and V define the arrow directions, respectively in x- and y-direction
U, V = np.meshgrid(3*X, 3*Y)

plt.figure()

plt.subplot(121)
plt.quiver(X, Y, U, V)
plt.title('Only autoscaling')

# Argument 122 denotes 1 row, 2 columns, second subplot. Notice that the number of rows and columns has to be equal every time, 
# where as the last number is the position where we want our subplot.
plt.subplot(122)
plt.quiver(X, Y, U, V)
# Here we specify the axes. How much extra space you need depends on the arrow size and direction,
# and must therefore be adapted each time
plt.axis([-6.5, 5.5, -6.5, 5.5])
plt.title('Manually set axes')

plt.show()


Contour plot

Further demos on contour plots and contour labels.

In the example below two types of contour plots are used, where contour and contourf draw contour lines and filled contours, respectively.

The call signature is contour([X, Y,] Z, [levels]), where X and Y are the coordinates of the values in Z, and Z  is the height values over which the contour is drawn.

Contour plots
import matplotlib.pyplot as plt
import numpy as np

def f(x, y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
 
x = np.linspace(0, 5, 60)
y = np.linspace(0, 5, 50)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig, axs = plt.subplots(1,3)
fig.suptitle('Three versions of the same contour plot')
axs[0].contour(X, Y, Z)
axs[1].contourf(X, Y, Z)
axs[2].contour(X, Y, Z, colors='black')

plt.show()

  • No labels