6. Plots in 1D#

Data visualization is an important skill for an engineer and there are many libraries in Python for doing so. We will use the foundation Matplotlib library and specifically the Pyplot package in this course.

Summary of commands#

In this exercise, we will demonstrate the following:

Making plots with Pyplot#

The standard syntax (best practice) for Pyplot is as follows:

import matplotlib.pyplot as plt    # alias
fig, ax = plt.subplots()           # create Figure and Axes objects
ax.plot(x, y)                      # or any other plotting function
plt.show()                         # show the figure underneath the code cell

Here is an example problem: The displacement of an object falling under the force of gravity is given by

\[ y = \dfrac{1}{2} gt^2 \]

where \(g\) is the acceleration due to gravity [units: m s\(^{-2}\)], \(y\) is the distance traveled [m], and \(t\) is time [s]. The following table gives the values of \(g\) for three different planets:

Planet

\(g\)

Earth

9.80 m s\(^{-2}\)

Jupiter

24.79 m s\(^{-2}\)

Mercury

3.72 m s\(^{-2}\)

Part 1#

Plot the distance fallen as a function of time near the surface of the Earth between \(0\) and \(10\) seconds, with an increment of \(1\) second. Add a title and \(x\)- and \(y\)-axis labels.

# import all packages
import numpy as np
import matplotlib.pyplot as plt

# calculate the data
t = np.linspace(0, 10, 11)
g = 9.80
y = 0.5 * g * t ** 2

# make the plot
fig, ax = plt.subplots()
ax.plot(t, y, c='b', ls='--')
ax.set(xlabel="Time [s]", ylabel="Distance fallen [m]", 
       title="Distance fallen on Earth")
plt.show()
# fig.savefig("my_figure.png", dpi=300, bbox_inches='tight')   # uncomment to save figure to disk
../_images/ac3d7444e34f8a7c69a19b3caf20157b86d8a55f87e16fa0048e4a563fcdd878.png

Notice how in the ax.plot() function we added extra arguments that defined the style of the line.

  • c is shorthand for color, which has many options.

  • ls is shorthand for linestyle, which also has many options.

  • See the documentation for the function to explore more options.

Challenge: What does ax.annotate() do? Can you get it to work?

Part 2#

You can plot multiple curves directly by calling ax.plot() (or another plotting function) multiple times. In MATLAB you may be used to writing hold on, but Python does it automatically!

We’ll plot the displacement curve for both Earth and Jupiter in the same figure and add a legend. Pay attention to the labeling syntax!

# import all packages
import numpy as np
import matplotlib.pyplot as plt

# calculate the data
t = np.linspace(0, 10, 11)
g_E = 9.80
y_E = 0.5 * g_E * t ** 2
g_J = 24.79
y_J = 0.5 * g_J * t ** 2

# make the plot
fig, ax = plt.subplots()
ax.plot(t, y_E, ls=':', label="Earth")
ax.plot(t, y_J, ls='dashdot', label="Jupiter")
ax.set(xlabel="Time [s]", ylabel="Distance fallen [m]")
ax.legend()
plt.show()
../_images/8566731d4318ea313abf6275bf798ebcca064f8e65ab569868120012c0c17df4.png

Part 3#

In some cases, we want all of our curves to be in the same figure, but different panels. To construct multiple sets of axes, we can use the nrows and ncols parameters of the plt.subplots() function. We’ll demonstrate this by plotting the curves for Earth and Jupiter in the same figure (adjusted to be larger!) on separate axes.

# import all packages
import numpy as np
import matplotlib.pyplot as plt

# calculate the data
t = np.linspace(0, 10, 11)
g_E = 9.80
y_E = 0.5 * g_E * t ** 2
g_J = 24.79
y_J = 0.5 * g_J * t ** 2

# make the plot
fig, ax = plt.subplots(figsize=(10,5), ncols=2)
ax[0].plot(t, y_E, ls=':', label="Earth")
ax[0].set(xlabel="Time [s]", ylabel="Distance fallen on Earth [m]")
ax[1].plot(t, y_J, ls='dashdot', label="Jupiter")
ax[1].set(xlabel="Time [s]", ylabel="Distance fallen on Jupiter [m]")
plt.subplots_adjust(wspace=0.3)
plt.show()
../_images/1999e27f6e83d2aac1d0f77099b4795a0f4ce31d240843156f8f810f6f65f566.png

In the second to last line, we added some additional padding (docs). You can try to see what happens when you comment out that line. Also, what if you add sharey=True into plt.subplots()?