Question

I am trying to add text on top of a panel of subplots as labels:

import numpy as np
import matplotlib.pyplot as plt
# Create figure
fig, axs = plt.subplots(5, 4, figsize=(6.83, 9.19))
# Plot something
for axes in axs.ravel():
    axes.plot(range(5))
# Add some labels
fig.text(0.25, 1.01, "Label #1", fontsize=10, fontweight='bold', ha='center')
fig.text(0.75, 1.01, "Label #2", fontsize=10, fontweight='bold', ha='center')
fig.text(0.125, 0.99, "Sublabel #1", fontsize=10, ha='center')
fig.text(0.375, 0.99, "Sublabel #2", fontsize=10, ha='center')
fig.text(0.625, 0.99, "Sublabel #3", fontsize=10, ha='center')
fig.text(0.875, 0.99, "Sublabel #4", fontsize=10, ha='center')
# Save figure
fig.tight_layout()
fig.savefig('./temp.png', dpi=300)

However, because the labels are above the figure, they cannot be seen in the saved figure (though they can be seen on the ipython qtconsole). Could anyone help me with this?

Was it helpful?

Solution

You can do:

fig.savefig('./temp.png', dpi=300, bbox_inches='tight')

to adjust the figure when saving. You can also set the figure size properly since the beginning, adding before the "Create figure":

plt.figure(figsize=(width, height))

OTHER TIPS

Thanks again to Saullo's answer, I think that answers my original question. However, I ended up using a different solution because I think this has better control of the page size:

import numpy as np
import matplotlib.pyplot as plt
# Create figure
fig, axs = plt.subplots(5, 4, figsize=(6.83, 9.19))
# Plot something
for axes in axs.ravel():
    axes.plot(range(5))
# Add some labels
fig.text(0.25, 1., "Label #1", fontsize=10, fontweight='bold', ha='center', va='top')
fig.text(0.75, 1., "Label #2", fontsize=10, fontweight='bold', ha='center', va='top')
fig.text(0.125, 0.98, "Sublabel #1", fontsize=10, ha='center', va='top')
fig.text(0.375, 0.98, "Sublabel #2", fontsize=10, ha='center', va='top')
fig.text(0.625, 0.98, "Sublabel #3", fontsize=10, ha='center', va='top')
fig.text(0.875, 0.98, "Sublabel #4", fontsize=10, ha='center', va='top')
# Save figure
fig.tight_layout()
fig.subplots_adjust(top=.95)
fig.savefig('./temp.png', dpi=300)

Basically, the trick is:

1) Add the va='top' to text, and let the y-coord of the text to be < 1 so they are within bounds;

2) Use fig.subplots_adjust(top=.95) to save space for the text. Note: this must be after fig.tight_layout()!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top