1.11. Visualization with matplotlib#

Reference: Chapter 1 of Computational Nuclear Engineering and Radiological Science Using Python, R. McClarren (2018)

1.11.1. Learning Objectives#

After studying this notebook, completing the activities, and asking questions in class, you should be able to:

  • Add multiple lines to a single plot

  • Specify the color, style, width, and other properties of a line

  • Add title, legend, and axes labels

  • Save figure to a PDF

  • Add grid lines

  • Look up advanced formatting options in matplotlib documentation and examples

1.11.2. Matplotlib Basics#

Matplotlib is a simple plotting tool that allows you to plot the arrays from NumPy. We already saw an example above. Matplotlib is designed to be intuitive, easy to use, and to mimic MATLAB syntax.

As an example, let’s plot the cardinal sine function:

\[\mathrm{sinc}(x) = \frac{\sin(x)}{x}\]
import matplotlib.pyplot as plt
%matplotlib inline 
import numpy as np
#make a simple plot
x = np.linspace(-100,100,1000)
y = np.sin(x)/x
#plot x versus y
plt.plot(x,y)
#label the y axis
plt.ylabel("sinc(x) [arb. units]");
#label the x axis
plt.xlabel("x [cm]")
#give the plot a title
plt.title("Line plot of the sinc function")
#show the plot
plt.axis([-100,100,-.4,1.05])

# Save the figure to our Google Drive folder Colab-20258
plt.savefig("figure.pdf")
plt.show()
../../_images/e38781940e5092aec8d10755827560ae2a155b364bed63f058baaa8b2ee24f38.png

Notice how I labeled each axis and even gave the plot a title. I also included the units for each axis. You should always do this in your work. Label-less plots are meaningless.

Class Activity

Locate and download the created PDF figure.

1.11.3. Customizing Plots#

You can also change the plot type.

x = np.linspace(-3,3,100)
y = np.exp(-x**2)
fig = plt.figure(figsize=(4,3), dpi=200)
plt.plot(x,y,"ro"); #red dots on the plot
plt.ylabel("$e^{-x^2}$ [arb. units]");
plt.xlabel("x [cm]")
plt.title("Plot of $e^{-x^2}$")
plt.axis([-3,3,0,1.05])
plt.show()
../../_images/58a49650eb5e81daedacfea4cce1a7dbd6fc9a5205f0844ad6bcdd4b9a58bac9.png
x = np.linspace(-3,3,100)
y = np.exp(-x**2)
fig = plt.figure(figsize=(4,3), dpi=200)
plt.plot(x,y,"ko-"); #black dots and a line on the plot
plt.ylabel("$e^{-x^2}$ [arb. units]");
plt.xlabel("x [cm]")
plt.title("Plot of $e^{-x^2}$")
plt.axis([-3,3,0,1.05])
plt.show()
../../_images/600ac6d2802df57ea66b18cb6872950714ac78ff5ed4a8a95f4aeb4d0e4887b6.png

There are many options you can adjust for the plot. For a full list, see http://matplotlib.org/users/pyplot_tutorial.html

Here are some more examples. One of the things you’ll notice is that in matplotlib you can include LaTeX mathematics in your labels by enclosing it in dollar signs. In LaTeX, to use Greek letters you use a backslash before the name of the letter, and other usually obvious characters. To find out how to do anything with LaTeX, just Google it.

x = np.linspace(-3,3,100)
y = np.exp(-x**2)
fig = plt.figure(figsize=(4,3), dpi=200)
plt.plot(x,y,marker="*", linewidth=0); 
plt.ylabel("$e^{-x^2}$ [arb. units]");
plt.xlabel("x (cm)")
plt.title("Plot of $e^{-x^2}$")
plt.axis([-3,3,0,1.05])
plt.show()
../../_images/88533000917888ec39223a1143c5f74c88d9411a27c5c4761ebb326ee50c575b.png
x = np.linspace(-3,3,100)
y = np.exp(-x**2)
fig = plt.figure(figsize=(4,3), dpi=200)
plt.plot(x,y,marker="",linewidth=4,color="maroon"); 
plt.ylabel("$e^{-x^2}$ [arb. units]");
plt.xlabel("x [cm]")
plt.title("Plot of $e^{-x^2}$")
plt.axis([-3,3,0,1.05])
plt.show()
../../_images/a31a47f72cf962dde04204c9b5aa8658b0827a8317eb52fea672ec5097672a0e.png

1.11.4. Plotting multiple lines#

You can also plot multiple lines on a plot. If you include the label for each plot, invoking the legend command puts the legend on the plot.

x = np.linspace(-3,3,100)

# Line 0
y = np.exp(-x**2)
plt.plot(x,y,marker="", color="r", 
         linestyle="--", label="$\sigma^2 = 1$"); 

# Line 1
y1 = np.exp(-x**2/2)
plt.plot(x,y1,color="blue", 
         label="$\sigma^2 = 2$")

# Line 2
y2 = np.exp(-x**2/4)
plt.plot(x,y2,color="black", 
         marker = "+", label="$\sigma^2 = 4$")

# Add labels, title, legend, etc.
plt.ylabel("$e^{-x^2/\sigma^2}$ (arb units)");
plt.xlabel("x (cm)")
plt.title("Plot of $e^{-x^2/\sigma^2}$")
plt.legend(loc="best")
plt.axis([-3,3,0,1.05])
plt.show()
../../_images/1e783fe1191c781c65a7370d03caf2edb695c0911d010cbc4393c370c92d51e9.png

Fancier plots are also possible. We’ll introduce whatever you need as we go.

Class Activity

Create a plot that compares sine and cosine from -2 π to 2 π with the following formatting rules:

  • Dashed red line for sine.

  • Solid blue line for cosine.

  • Legend located in the lower left corner.

  • Label the axes with \(x\) and \(f(x)\)

  • Add grid lines.

# Add your solution here
Hide code cell output
../../_images/c6839f3f9832eddcafa3aa545aacc8fe673d77119c209bb44c93035a0d81256a.png

1.11.5. Learning More#

If you would like to learn more or delve into more complex plotting, below are some links to various matplotlib documentation:

Tutorials

Getting Started

Examples

Matplotlib is a powerful tool that can display dozens of kinds of graphs for applications even outside of chemical engineering, so it’s helpful to be familiar with the available documentation for when you may need to reference it.