Using Matplotlib
Matplotlib is a core Python package for plotting.
Documentation
You can find documentation for Matplotlib here. Tutorials can also be found in the documentation.
Importing
import matplotlib.pyplot as plt
Create a plot
There are several approaches to using Matplotlib's code to generate plots. It can be quite confusing, given all of the options. This complexity is partly due to historical reasons, but also down to the enormous amount of flexibility available in Matplotlib. Below is the recommended usage.
Create a figure and axis/axes
This line creates a figure and single axis. Plots with be created inside the
axis/axes. Note that calling plt.show()
will open a popup window showing your
plot.
fig, ax = plt.subplots()
# Plot a scatter plot
ax.scatter([1, 2, 3], [1, 2, 3])
plt.show()
If you would like two plots side-by-side (note ncols
):
fig, ax = plt.subplots(ncols=2)
# Create a scatter plot on the left hand side:
ax[0].scatter([1, 2, 3], [1, 2, 3])
# Create a scatter plot on the right hand side:
ax[1].scatter([1, 2, 3], [1, 2, 3])
If you would like two plots, one on top of the other (note nrows
):
fig, ax = plt.subplots(nrows=2)
# Create a scatter plot on the left hand side:
ax[0].scatter([1, 2, 3], [1, 2, 3])
# Create a scatter plot on the right hand side:
ax[1].scatter([1, 2, 3], [1, 2, 3])
If you want a 2x2 grid of plots (below, only the top two axes will contain plots):
fig, ax = plt.subplots(nrows=2, ncols=2)
# Create a scatter plot on the top left hand side:
ax[0,0].scatter([1, 2, 3], [1, 2, 3])
# Create a scatter plot on the top right hand side:
ax[0,1].scatter([1, 2, 3], [1, 2, 3])
Plot types
Matplotlib has several plot types available. Most of the time, you will only need three. You can find more types in the documentation (most plot types are available).
x_data = [1, 2, 3]
y_data = [1, 2, 3]
ax.plot(x_data, y_data) # Scatter plot
ax.scatter(x_data, y_data) # Line plot
ax.bar(x_data, y_data) # Bar plot
Note that the appearance of these plots can be modified. For example a line-and-scatter plot can be created like so:
ax.scatter(x_data, y_data, "-o")
There are many other options for setting the line, bar and scatter styles, widths, etc. so you should be able to achieve any look you want.
Saving a figure
It is usually best to save a figure before using plt.show()
(otherwise the
saved figure may be empty). Below, a plot is saved as a 600 dpi png file.
Calling plt.close()
is best practice when you are finished with a figure to
free up prograf memory and prevent confusion if you create another plot later.
x_data = [1, 2, 3]
y_data = [1, 2, 3]
ax.plot(x_data, y_data)
plt.savefig("plot.png", dpi=600)
plt.close()
Modifying Plot Appearances
Note that below, we are using the fig, ax = plt.subplots()
method for creating
an interacting with a plot. Other ways of plotting require different methods for
updating the appearance, which you can find in the Matplotlib documentation.
Line styling
ax.plot([1, 2, 3], [1, 2, 3], color='blue', linewidth=3, linestyle='--')
More options can be found in the documentation.
Scatter Styling
Here, s=50
means that the marker size is set to 50. The facecolor
is the
colour of the fill of the marker, whilst edgecolor
is the colour around the
edge of each marker.
ax.scatter([1, 2, 3], [1, 2, 3], s=50, facecolor='C0', edgecolor='k')
Note that you can also pass lists of values to s
, facecolor
and edgecolor
to determine the appearance of individual markers. For example:
ax.scatter([1, 2, 3], [1, 2, 3], s=[10, 20, 30])
More options can be found in the documentation.
Change the axis titles
ax.set_xlabel("time/ s", fontsize=12, color="black")
ax.set_ylabel("concentration/ M", fontsize=12, color="black")
You can also style the text using LaTeX syntax:
ax.set_ylabel("$\sigma$[CO$_{2}$]/ M")
Set tick label appearance
The line below changes the x axis tick labels font size to 20.
ax.tick_params(axis='x', labelsize=20)
More details are provided here.
Add a legend to an axis
Note that a labels must be present for the legend to display:
ax.scatter(x_data, y_data, label="scatter")
ax.plot(x_data, y_data, label="line")
ax.legend()
The appearance and position of the legend can be set (see here).
Set Tick Positions
ax.set_xticks([0, 30, 60, 90], ['zero', '30', 'sixty', '90'])
ax.set_yticks([-1.5, 0, 1.5]) # note that we don't need to specify labels
Set axis limits
ax.set_xlim([0, 1])
ax.set_ylim([2, 3])
Alternatively:
ax.axis([0, 1, 2, 3])
Add an annotation
ax.annotate("Hello", xy=(0,1), ha="center", va="center")
More details can be found here.