Plotting with Matplotlib#

A straigh forward and simple library for plotting data is matplotlib.

See also:

import math
import matplotlib.pyplot as plt

For plotting, we need values to plot. Let’s start with a list of x-values:

x_values = range(0, 360, 10)

To compute the corresponding y-values, we use a for loop, that creates a new list of values equal to the x_values list and computes a new number for each entry:

y_values = [math.sin(x * math.pi / 180) for x in x_values]

Then, let’s draw a simple plot

plt.plot(x_values, y_values)
[<matplotlib.lines.Line2D at 0x12aa15610>]
../_images/e620deb89cbd86f3fa569913c33be9a662f355a9cb1f19b1f010b89ca3e02773.png

Plots can be modified in various ways.

plt.plot(x_values, y_values, '*')
[<matplotlib.lines.Line2D at 0x12ab6c3d0>]
../_images/0a8dc69416fee0a0dee663e5ea57d64e73b7add7f64c73002e9ad42a15ec904d.png
plt.plot(x_values, y_values, color='green')
[<matplotlib.lines.Line2D at 0x12abddc10>]
../_images/223e0f53524726bdd7a51920c7e3366c9b83969d7fd6f624a6d40c5a0f473c3a.png

If you want to combine multiple plots in one figure, you can do this:

plt.plot(x_values, y_values, color='green')

neg_y_values = [- y for y in y_values]
plt.plot(x_values, neg_y_values, color='magenta')
[<matplotlib.lines.Line2D at 0x12ac5d130>]
../_images/21c6eb19fb9e7e94958e202524cdd399ca30e4f0e9f8c1efdb5240fbc941e6ff.png

Sub-plots#

The subplots command allows you to have multiple plots in one block.

fig,axs = plt.subplots(1, 2)

axs[0].plot(x_values, y_values, color='green')
axs[1].plot(x_values, neg_y_values, color='magenta')
[<matplotlib.lines.Line2D at 0x12acffc10>]
../_images/e4918ad866cee2a895f19a0566ef5427879e3ed0cd8956fd945edb2fc09da501.png
fig,axs = plt.subplots(2, 3, figsize=[15,10])

axs[0,0].plot(x_values, y_values, color='green')
axs[0,1].plot(x_values, neg_y_values, color='magenta')
axs[0,2].plot(x_values, neg_y_values, color='red')
axs[1,0].plot(x_values, neg_y_values, color='cyan')
axs[1,1].plot(x_values, neg_y_values, color='blue')
axs[1,2].plot(x_values, neg_y_values, color='yellow')
[<matplotlib.lines.Line2D at 0x12aec7190>]
../_images/2e7519c2ff22eb883482bc2389850013237ae38d70b7b76b4c5955f5884f84f8.png

Exercise#

Plot sinus and cosinus of values between 0 and 360 degrees in one plot.