10. Plotting#

Saleh Rezaeiravesh, saleh.rezaeiravesh@manchester.ac.uk
Department of Mechanical and Aerospace Engineering, The University of Manchester, Manchester, UK


Overview: In Python, there are various packages for visualisation of the data. One of the most frequently used package is `matplotlib`:
https://matplotlib.org/stable/index.html

In this notebook, elementary syntaxes for plotting 2D graphs in matplotlib are opresented.

10.1. Import matplotlib#

matplotlib has several classes, but the main one that we use here is pyplot. This can be imported as below:

import matplotlib.pyplot as plt

10.2. 2D plot of a single graph#

Assume we want to plot \(y\) versus \(x\), where we have numpy arrays for these two variables. First, we create some data:

#first create some test data
import numpy as np

x = np.linspace(0,2*np.pi,100)   #equi-spaced x-values
y = np.sin(3.*x)                    #y values at x

Plotting is simple, we use plot from class plt (imported above), and then we should use show() to see the plot.

plt.plot(x,y)
plt.show()
../../_images/ead364a74d727adfb7d7971d8896f955b3d7cc34e1ff6dee30d555c97f645679.png

10.2.1. Line’s color and style#

A plot has several attributes including:

  • line style, ls: simply you can write - (solid line), : (dotted line), -- (dashed line)

  • line color, color

  • line width, lw

plt.plot(x,y,'--',color='red',lw=2)
plt.show()
../../_images/44bbd3ca9759419e05dcb030ebfa0f82593e007af0dd2ee6b29fb4fd3f11f718.png

You can see the list of some default colors in matplotlib in this link.

10.2.2. Add markers#

You can use markers solely or with lines. By default, markers appear at values of x. There are different markers, such as o (circle), x (cross), s (square), etc. See the full list here.

plt.plot(x,y,'-ob')
plt.show()
../../_images/2cdd4c027344448d63308a2f0678fb328e516a02e292c5128209541b910df112.png

Markers can have a different face color specified by mfc. Note that mfc='none' returns hollow markers.

plt.plot(x,y,'--or',mfc='k')
plt.show()
../../_images/413c3e1195e7ce78a522e4e39969460029c43c472acb09df46dc657b55d4f347.png

10.2.3. Axis label#

For the axes label, we can use pure text as string, Latex math expressions (provided within $  $ as usual), or a combination of the two. If you are using the latter, make sure you add an r before the string. Also, the font size of the labels can be easily specified.

plt.plot(x,y,'-k')
plt.xlabel('$x$',fontsize=18)                   #x label
plt.ylabel(r'$y=\sin(3x)$',fontsize=12)         #y label
plt.show()
../../_images/90895b742f4c5065922960ec720dedc11d4eedc11cd0b23e7c3dc04ffcb611f7.png

10.2.4. Figure size#

This width and height of the figure can be set through the 1st and second arguments of figsize:

### control the figure size
plt.figure(figsize=(8,3))
plt.plot(x,y,'-k')
plt.show()
../../_images/c8e4b8acb17ac6d182079b0023370df5f8defca344761eaf426cf6d71423417b.png

10.2.5. Size of the axes’ ticks#

There are different ways to set the size of the ticks on the axes, including using plt.xticks() and plt.yticks():

plt.figure(figsize=(8,3))
plt.plot(x,y,'-k')
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.show()
../../_images/42e9347419025fc9616c5cd91a8c3c038e3b22f8440c1c145e6ec7c5b3d826c4.png

10.2.6. Add grid#

plt.plot(x,y,'-k')
plt.grid()
plt.show()
../../_images/81116c89b43faf83abddb06ea107cfd56371dcd6dd92bda2f07cb29180983c88.png

10.3. Multiple graphs in one plot#

Seomtimes we need to plot two or more graphs in one plot. To distinguish between multiple graphs, different line styles and coloes with and without markers can be used. A label can be assigned to each graph using label key in plot function. To show the labels as a legend, call plt.legend which has several parameters including loc (location of the legend on the plot) and fontsize. For a full list of parameters, see this link.

Let’s create another graph and plot it along the above curve in one plot.

y2=0.5*np.cos(0.5*x**2)
plt.figure(figsize=(8,4))

plt.plot(x,y,'-b',label=r'$\sin(3x)$')      #plotting the first graph 
plt.plot(x,y2,'--r',label=r'$0.5\cos(x^2/2)$')   #plotting the second graph

plt.xlabel(r'$x$',fontsize=16)      
plt.ylabel(r'$y$',fontsize=16)

plt.xticks(fontsize=16)
plt.yticks(fontsize=16)

plt.legend(loc='best',fontsize=14)   #add legend with location set to be the best one
plt.show()
../../_images/de87d2c7782fa4417601b33bb1fe51c49d5c4f8713d60f3406571fb76a15c75e.png

10.4. Multiple graphs in subplots#

We can have a set of subplots within each one or more plots are provided. Use plt.subplot(nRows, nColumn, id) to create an array of subplots, where:

  • nRows: number of rows

  • nColumn: number of columns

  • id: plot id - it goes from 1 to nRows*nColumn.

Once all subplots are defined, write plt.show().

plt.figure(figsize=(10,5))

#subplot 1
plt.subplot(1,2,1)   #indices: 1 row, 2 column, first subplot
plt.plot(x,y,'-b',label=r'$\sin(x)$')
plt.xlabel(r'$x$',fontsize=16)
plt.ylabel(r'$y$',fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.legend(loc='best',fontsize=14)   #add legend

#subplot 2
plt.subplot(1,2,2)   #indices: 1 row, 2 column, second subplot
plt.plot(x,y2,'--r',label=r'$\cos(2x)$')
plt.xlabel(r'$x$',fontsize=16)
plt.ylabel(r'$y$',fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.legend(loc='best',fontsize=14)   #add legend

plt.show()  #show both subplots
../../_images/20bf39ed8c0b7d7bce96ef1206436f106435d6357dc30b72a57125dc3dfa2409.png

We can add other graphs to each of these subplots. Let’s add an array and a list of discrete data, for instance (shown by markers).

#list of data
a=[0,0.5,4,2.8,5,1]
b=[-0.25,0,0.39,0.6,-0.4,0]

#a new function using numpy arrays as input
y2=np.cos(4*x)*np.sin(2*x)
plt.figure(figsize=(14,3))

#subplot 1
plt.subplot(1,2,1)   #indices: 1 row, 2 column, first subplot
plt.plot(x,y,'-b',label=r'$\sin(3x)$')
plt.plot(a,b,'o k',ms=7, label='Some random data')
plt.xlabel(r'$x$',fontsize=16)
plt.ylabel(r'$y_1$',fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.legend(loc='best',fontsize=10)   #add legend


#subplot 2
plt.subplot(1,2,2)   #indices: 1 row, 2 column, second subplot
plt.plot(x,y2,'--r',label=r'$0.5*\cos(x^2/2)$')
plt.xlabel(r'$x$',fontsize=16)
plt.ylabel(r'$y_2$',fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.legend(loc='best',fontsize=10)   #add legend
plt.show()  #show both subplots
../../_images/6c79a3d4bd177e765cf7229dd3ae03fb4804b8fc9fd022422d3d1b62b04bb394.png

10.4.1. Save a plot#

To save a plot made by matplotlib, we can use savefig('PATH/figName'). Make sure the path exists on the disk. figName should contain the image type, like .png, .pdf, etc. If you want to show the plot, write plt.show() after plt.savefig().