Messor
Messor

Reputation: 101

How to set a title inside subplots using matplotlib?

enter image description hereI am creating a figure with subplots using:

fig, axs = plt.subplots(5, sharex=True, sharey=True, gridspec_kw={'hspace': 0})

Then I want to add a title to each subplot, but with the title inside the subplot. I tried using

for i in range(0,5):
    axs[i].set_title('title = ' + str(i), pad = -15)

But this approach creates the last title again in the subplot above, for reasons I don't yet understand. I also tried appending an additional subplot, but couldn't find a convenient way to get rid of it again.

Upvotes: 2

Views: 1399

Answers (1)

DavidG
DavidG

Reputation: 25362

I don't know why this happens using pad. However, a workaround might be to use the argument y= to specify a position for the title text, along with changing the vertical alignment of the text:

fig, axs = plt.subplots(5, sharex=True, sharey=True, gridspec_kw={'hspace': 0})

for i in range(0,5):
    axs[i].set_title('title = ' + str(i), y=0.8, va="top")

enter image description here

Upvotes: 3

Related Questions