Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing text outside the figure limits

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?

like image 704
Yuxiang Wang Avatar asked Oct 20 '25 14:10

Yuxiang Wang


2 Answers

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))
like image 170
Saullo G. P. Castro Avatar answered Oct 23 '25 04:10

Saullo G. P. Castro


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()!

like image 38
Yuxiang Wang Avatar answered Oct 23 '25 02:10

Yuxiang Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!