我正在尝试在子图的面板上添加文本作为标签:
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)
但是,因为标签高于图形,所以在保存的图中无法看到它们(尽管可以在ipython qtconsole上看到它们)。有人可以帮我这个吗?
答案 0 :(得分:3)
再次感谢Saullo的回答,我认为这回答了我原来的问题。但是,我最终使用了不同的解决方案,因为我认为这可以更好地控制页面大小:
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)
基本上,诀窍是:
1)将va='top'
添加到文本中,并让文本的y-coord为< 1所以他们在界限内;
2)使用fig.subplots_adjust(top=.95)
来节省文本空间。注意:这必须在fig.tight_layout()
之后!
答案 1 :(得分:1)
你可以这样做:
fig.savefig('./temp.png', dpi=300, bbox_inches='tight')
保存时调整数字。您也可以从头开始正确设置图形尺寸,在“创建图形”之前添加:
plt.figure(figsize=(width, height))