python - 将图文本添加到子图底部的问题

标签 python matplotlib

我正在尝试使用 plt.figtext 添加一系列脚注到一组子图,当我使用 plt.savefig() 打印到文件时无法让它们全部显示出来命令,或 %matplotlib notebook保存到文件选项。

脚注列表相当长,看起来像(渲染到屏幕上时,效果很好):Desired output of figures and footnotes

但是,当我打印到文件时,它们被切断:Undesired output

我将子图的图形大小设置为 plt.figure(figsize=(7,10)) 并使用plt.tight_layout()设置子图的格式,以便轴不会与标题混在一起。

我一生都在努力寻找一种方法来扩展输出的大小以解释脚注和子图,但绝对没有运气。无论怎么想,这似乎都不是一个不合理的用例。

编辑

创建每个子图后会生成文本,大致如下:

plt.legend(loc=6, fontsize=10)
#plt.legend(bbox_to_anchor=(1.0, 1), loc=2, borderaxespad=0.)
plt.xlim(0, 45)
plt.ylim(2.5, 5.5)
plt.xlabel('Distance (km)', alpha=.75)
plt.ylabel('Pace (min/km)', alpha=.75)
plt.title('Top 4 Male Finishers and SA 2016 Twin Cities Marathon Timed$^1$ Splits$^2$')
plt.figtext(0.814, 0.01, '1 Provided by mtecResults', horizontalalignment='right', fontsize=6) 
plt.figtext(0.88, 0.0, '2 Mean time per unit distance between two points', horizontalalignment='right', fontsize=6) 
plt.figtext(0.845, -0.01, '3 SA Finished 670 out of 4716 Males', horizontalalignment='right', fontsize=6)
plt.figtext(0.845, -0.02, '4 SA Finished 754 out of 4756 Males', horizontalalignment='right', fontsize=6)

最佳答案

当然,有多种选项可以确保保存时某些文本标签实际上位于图形内。

1。 bbox_inches 参数

您可以选择不使用plt.tight_layout(),因为这会忽略作为文本标签添加的文本。然后,您可以使用 plt.savefigbbox_inches 参数:

plt.savefig("output.png", bbox_inches = "tight")

此方法会增加图形大小,直到包含所有文本。

放置文本最好使用 verticalalignment ="top" 并将测试放置在图形坐标中靠近 y=0 的位置。示例:

import matplotlib.pyplot as plt
plt.gca()

text = """1 Provided by mtecResults
2 Mean time per unit distance between two points
3 SA Finished 670 out of 4716 Males
4 SA Finished 754 out of 4756 Males"""

plt.figtext(0.05,0.00, text, fontsize=8, va="top", ha="left")

plt.savefig(__file__+".png", bbox_inches = "tight")
plt.show()

enter image description here

2。为图形添加边距。

您可以使用plt.subplots_adjust(bottom=0.4)在轴周围腾出更多空间,然后可以用文本填充。对于其他尺寸,请使用参数 topleftright,具体取决于文本所在的位置。
此选项要求文本位于图形内。它不会改变图形尺寸,但会减小轴的尺寸。

放置文本最好使用 verticalalignment ="bottom" 并将测试放置在图形坐标中靠近但高于 y=0 的位置。示例:

import matplotlib.pyplot as plt

plt.gca()
plt.subplots_adjust(bottom=0.2)

text = """1 Provided by mtecResults
2 Mean time per unit distance between two points
3 SA Finished 670 out of 4716 Males
4 SA Finished 754 out of 4756 Males"""

plt.figtext(0.05,0.01, text, fontsize=8, va="bottom", ha="left")

plt.savefig(__file__+"2.png")
plt.show()

enter image description here

关于python - 将图文本添加到子图底部的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158914/

相关文章:

python - 删除字符串中括号内所有出现的单词的方法?

python - 在 python 中使用 SVM 进行回归置信度

python - Matplotlib 支持 Qt5 吗?

pandas - Seaborn:如何更改显示图的图形大小?

Python多体动画不起作用

Python - 即使在使用 'remove_job' 后,Apscheduler 也不会停止作业

python - 为什么 Pandas 拒绝读取 9 个世纪后的日期?

python 2.7.5,获取多个用户输入以加载超过 1 个数组/列表,循环问题

python - 当传递命名参数时,matplotlib 不会绘图

python - 控制 matplotlib .svg 图形的类和 id 属性?