简体   繁体   中英

matplotlib: (Automatically) Ensure text fits inside figure

I am trying to create some violin plots and put some text over each plot. My problem is that the text sometimes gets printed outside the figure. Does matplotlib provide a way to automatically extend the y-axis if text is outside there?

Minimal example:

import matplotlib.pyplot as plt

plt.violinplot([1, 2, 3])

plt.gca().text(1.1, 2.5, "foo")  # Ok
plt.gca().text(1.1, 3.2, "bar")  # Outside plot
plt.gca().text(1.1, 4.0, "baz")  # Not even printed

plt.savefig("plot.png")

Result:
在此处输入图像描述

Modify ylim:

import matplotlib.pyplot as plt

plt.violinplot([1, 2, 3])

plt.gca().text(1.1, 2.5, "foo")  # Ok
plt.gca().text(1.1, 3.2, "bar")  # Outside plot
plt.gca().text(1.1, 4.0, "baz")  # Not even printed
plt.ylim(.8,5)
plt.tight_layout()

plt.savefig('plot.png')

在此处输入图像描述

You could use plt.tight_layout();

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM