For a plot like this:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey=True)
ax1.plot(x, y)
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')
how can I add subtitles for a row?. It should look like this:
I made “Title1” and “Title2” with photoshop, how can I add them to the plot in python?
4
Answers
This is fairly simple to do; call
set_title
on the subplotsTo make a title for a plot with subplots, matplotlib has
pyplot.suptitle
. Since there can only be onesuptitle
per figure it does not solve the problem if you want to have two rows of figures.Using
plt.text()
one can set text to an axes, which is also not wanted here, so I would suggest to useplt.figtext
It may then be required to adjust the spacingbetween the rows of the subplots using
plt.subplots_adjust(hspace = 0.3 )
You can do it by adding 3 lines of code as below:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
New in matplotlib 3.4.0
We can now do this with built-in suptitles for subfigures.
First create a 2×1 subfigure grid via
Figure.subfigures
. Then for each subfigure, give it its own 1×2 subplot grid and suptitle:Note: it’s also possible to put subfigures into an existing
plt.subplots
grid viaFigure.add_subfigure
as shown in how to plot subfigures.