Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


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.


Info

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



Panel
borderColor#dfe1e5
bgColor#eff9ff
borderWidth2
titlePage content

Table of Contents

outlinetrue


Tips and tricks

Datvisualization is mainly about making your data easy to understand in a fast, interesting manner. It is therefore important to present your plots as clean, informative and proffesional as possible. We will now look at some small changes to your code that will help you achieve this. Also, check out our page Tips and tricks for coding.

Figure and plot appearance 

Use the fact that the appearance of your figures and plots are changeable. The easiest and most important are such as xlabel(), ylabel() and title() that will help you describe your plot, while legend(), colors and linestyles will seperate different plots from eachother. More advanced changes may be making the axes log-scaled, or using markers to specify a certain area of the plot. In order to get better at this, look at other plots to see what they have done well, and what could have been done better. A great place to look for inspiration is the offical Matplotlib webpage, where a number of examples are already made.

Mathematical text

Matplotlib supports using TeX when writing mathematical expressions. This makes math text very presentable while beeing easy to write. We recommend you to visit Matplotlib's "Writing mathematical expressions" to get a complete tutorial. Here is an example:


Code Block
languagepy
plt.title(r'$\phi = \frac{\zeta_{a} g}{\omega} e^{k z} cos(\omega t + k x)$')

produces Image Added.

Simple plot

Simple plots

Info

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


Code Block
languagepy
titleSimple plot code
collapsetrue
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]')

# NeedWe need to call the show() function at the end to display myour figure
plt.show()

Code Block
languagepy
titleMultiple plots in same figure
collapsetrue
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.
# Specifying the location of legend is optionally, but may be 'left', 'lower right' or 'best'.
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()


Info

More in-depth plot() documentation and legend() documentation.

Multiple figures and subplots

Info

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


Code Block
languagepy
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.

Code Block
languagepy
titleA single plot
collapsetrue
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.

Code Block
languagepy
titleVertically stacked subplots
collapsetrue
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].

Code Block
languagepy
titleVertically stacked subplots (alternative)
collapsetrue
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.

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


Image AddedImage AddedImage Added

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:.


Info

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.


Code Block
languagepy
titleStacking subplots in two directions
collapsetrue
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()

Image Added

Multiple figures with subplots

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

Note

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?


Code Block
languagepy
titleMultiple figures
collapsetrue
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:

Code Block
languagepy
titleMultiple figures, current method
collapsetrue
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


Info

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


Quiver plot

Quiver plots a 2D vector field of arrows.

Info

More in-depth quiver documentation and functions.


Code Block
languagepy
titleSimple quiver plot
collapsetrue
import numpy as np
import matplotlib.pyplot as plt


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

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

# Call signature: quiver([X, Y], U, V = np.meshgrid(X, Y)

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

7

Note

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 with only autoscaling vs manually is shown below.


Code Block
languagepy
titleQuiver autoscaling vs manually set axes
collapsetrue
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()

# Argument 121 in subplot() below denotes 1 row, 2 columns, first subplot. sublot(121) is then current.
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()

Image Added


Contour plot

Info

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. Levels is optional, and determines the number and positions of the contour lines / regions.

Code Block
languagepy
titleContour plots
collapsetrue
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()

Image Added


3D Plot

3D Plotting is not used in most courses, but may be used as a great tool of learning, as the visual aspects of plotting often are even more reinforced in 3D plots. In this chapter, we want to show you how easy it is to set up a simple 3D plot using Matplotlib. Check out Matplotlib's tutorial on 3D Plots if you want to learn more about the possibilities in 3D.

Info

3D Plots as a tool of learning may be especially useful when learning about linear wave theory in the course TMR4247 - Marine Technology - Hydrodynamics.


Code Block
languagepy
title3D Plot
collapsetrue
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

# Setting the axes to 3D
ax = Axes3D(fig)        
X, Y = np.meshgrid(np.arange(0, 2*np.pi, 0.2), np.arange(0, 2*np.pi, 0.2))
Z = np.sin(X)

# Making the 3D plot as a surface plot, where X, Y and Z is data values as 2D arrays
# The arguments here are in the same format as used in Contour plots
# Also specifing a colormap to make our surface easier to interpet
ax.plot_surface(X, Y, Z, cmap='Blues')
ax.set_xlabel('X-label')
ax.set_ylabel('Y-label')
ax.set_zlabel('Z-label')
ax.set_title('3D Plot')

plt.show()

Image Added



Plotting animation

Plots are often time-dependent, and even though most of them are easily interpeted by choosing a specific t0, making a small animation may help you get some extra insight to how the plot actually changes with time. We will now set up a simple animation using the 3D plot as an example. Because our main goal with this animation is to get a better understanding of how our function changes with time, we will not put to much effort into the aesthetics of our animaiton.


Info

Keep in mind that this is not the best approach when making good, smooth animations, but rather a fast and easy setup.


Code Block
languagepy
titlePlotting animation
collapsetrue
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = Axes3D(fig)
X, Y = np.meshgrid(np.arange(0, 2*np.pi, 0.2), np.arange(0, 2*np.pi, 0.2))

# Setting a time interval
dt = 0.1                

# We have set our range from 0 to 10000 to make sure it runs as long as we want, and we'll then close it ourself
for i in range(0, 10000):
    # Our function for Z has to be dependent on some non-constant value
    # We have chosen to increase 'dt' each loop
    dt = dt + 0.1
    Z = np.sin(X + dt)

    # Our plotting has to be done inside the loop, as we want to redraw it mulitple times
    ax.plot_surface(X, Y, Z, cmap='Blues')

    # Since we are using the 'ax.clear()' at the end to clear all previous drawings, we need to specfiy all axes inside the loop
    # If we choose not to clear, we can move this outside the loop
    ax.set_xlabel('X-label')
    ax.set_ylabel('Y-label')
    ax.set_zlabel('Z-label')
    ax.set_title('3D Animation')

    # Here we pause the system for some time, in order for us to be able to watch as the plot changes
    plt.pause(1/60)

    # Lastly, we clear all previous drawings, as we usually only want to see the plot at the current time value
    ax.clear()
    
plt.show()


Info

The animation below is slightly altered from the code above in order to make it a GIF.

Image Added


If you want to learn about the more advanced, preffered methods of animation in Matplotlib, matplotlib.animation is a good place to start. A basic example is shown below.

Code Block
languagepy
titleBasic example using matplotlib.animation
collapsetrue
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: vanderplas@astro.washington.edu
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# Initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# Animation function. This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# Call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# The line below will save the animation as a GIF if uncommented.
# anim.save('basic_animation.gif', fps=30, writer='imagemagick')

plt.show()

Image Added

Info

More examples by the same author is found at this page, e.g. a double pendulum.


Exercises and solutions

If you want have a look at some exercises and solutions regarding NumPy, Matplotlib and data visualization, visit Exercises and solutions, data visualization in Python.

Info

The exercises provided will have a varying degree of difficulty, thus including more advanced and detailed methods than described here.


Other recommended tutorials on data visualization

  • Department of Statistics at the University of California, Berkeley, has made great tutorial on plotting using Matplotlib. This is really worth checking out: link.


BibTeX Display Table