= plt.figure() # an empty figure with no Axes fig
<Figure size 640x480 with 0 Axes>
Before we start creating plots, let’s take a look at the basic components of a plot in matplotlib
:
Figure in matplotlib is essentially the entire plot or image. This is the top-level container that holds all the other elements of the plot.
Axes is the region of the plot that contains the data. This is where the data is actually plotted. A figure can have multiple axes.
Axis (not to be confused with Axes) is the number line that represents the scale of the plot (e.g., x-axis, y-axis).
Axis labels are the labels that describe the axis. They are usually placed at the end of the axis.
An axis can have multiple ticks and labels.
Ticks are the marks on the axis that represent the scale of the plot.
set_xticks()
and set_yticks()
are used to set the ticks on the x-axis and y-axis, respectively.
fig, ax = plt.subplots(figsize=(3,3)) # a figure with a single Axes
# ticks are the values used to show specific points on the coordinate axis
# tick labels are the values shown at the ticks
# set_xticks() and set_yticks() are used to set the tick locations
ax.set_xticks([0, 1, 2, 3, 4]); # Set the x-ticks
Tick labels are the labels that describe the ticks. They are usually placed below the ticks.
set_xticklabels()
and set_yticklabels()
are used to set the tick labels
The title of the plot.
# a figure with a single Axes
fig, ax = plt.subplots(figsize=(3,3))
# Add a title to the figure
fig.suptitle('Title', fontsize=16);
For a
# a figure with a 2x2 grid of Axes
fig, ax = plt.subplots(2, 2, figsize=(6,6))
# Add a title to the entire figure
fig.suptitle('Super Title');
# a figure with a single Axes
ax[0][0].set_title('Top left');
ax[0][1].set_title('Top right');
ax[1][0].set_title('Bottom left');
ax[1][1].set_title('Bottom right');
A box that explains the meaning of the different colors or line styles in the plot.
# a figure with a single Axes
fig, ax = plt.subplots(figsize=(3,3))
# Legend is a box that labels the lines in a plot
# Plot some data on the Axes
ax.plot([1, 2, 3, 4], [1, 4, 2, 3], label='line 1')
ax.plot([1, 2, 3, 4], [2, 3, 3, 2], label='line 2')
# Add a legend
ax.legend(title='Legend', loc='upper right');
The lines that help to visually separate the different parts of the plot.
The style of the plot can be customized using the plt.style
parameter.
Some of the available styles are:
dark_background
seaborn
ggplot
fivethirtyeight
bmh
grayscale
You can save the plot as an image file using the plt.savefig()
function.