gpt4 book ai didi

python - 显示图形限制之外的文本

转载 作者:行者123 更新时间:2023-11-28 22:49:39 27 4
gpt4 key购买 nike

我正在尝试在子图面板的顶部添加文本作为标签:

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上可以看到)。谁能帮我解决这个问题?

最佳答案

再次感谢 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坐标为<1,这样它们就在边界内;

2) 使用 fig.subplots_adjust(top=.95) 为文本节省空间。注意:这必须在 fig.tight_layout() 之后!

关于python - 显示图形限制之外的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23532036/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com