spore234 spore234 - 8 days ago 5
Python Question

add subtitles for rows of a plot

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:

enter image description here

I made "Title1" and "Title2" with photoshop, how can I add them to the plot in python?

Answer

To make a title for a plot with subplots, matplotlib has pyplot.suptitle. Since there can only be one suptitle 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 use plt.figtext

It may then be required to adjust the spacingbetween the rows of the subplots using plt.subplots_adjust(hspace = 0.3 )

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')

plt.figtext(0.5,0.95, "A tremendously long title that wouldn't fit above a single figure", ha="center", va="top", fontsize=14, color="r")
plt.figtext(0.5,0.5, "Yet another multi-worded title that needs some space", ha="center", va="top", fontsize=14, color="r")
plt.subplots_adjust(hspace = 0.3 )
plt.savefig(__file__+".png")
plt.show()

enter image description here

Comments