我想用matplotlib
在绘图中添加一些方框注释。有没有办法为文本框指定一个固定的宽度?我希望我的注释中可以有一些随机的文本,这些文本会自动调整,而不是调整到侧面,而是从上到下。
下面是一个最小的例子:
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, TextArea
fig, ax = plt.subplots()
t = TextArea("Test 1")
xi, yi = 0.05, 0.1
ab = AnnotationBbox(t, xy=(xi, yi))
ax.add_artist(ab)
t = TextArea("Test 2 blah blah blah")
xi, yi = 0.1, 0.15
ab = AnnotationBbox(t, xy=(xi, yi))
ax.add_artist(ab)
# something along the lines of creating a rectangle of fixed width and having some text inside it
width, height = 0.025, 0.05
xi, yi = 0.2, 0.1
m = matplotlib.patches.Rectangle((xi - width / 2, yi - height / 2), width, height)
ax.add_patch(m)
ax.set_ylim([0, 0.3])
ax.set_xlim([0, 0.3])
这将生成以下图:
正如您所看到的,Test 2 blah blah blah
会自动将周围的框调整到边上,而我希望指定一定的宽度,超过这个宽度后,剩余的文本将写在下一行上。我知道matplotlib.offsetbox.AnnotationBbox
有一些参数,比如xybox
、xycoords
和boxcoords
,但我还没有找到任何方法来设置它们,使注释的行为像这样。我还查看了pyplot
模块(或Axes
类的text()
方法)中的文本函数,但没有找到任何指定宽度的方法。任何帮助都是非常感谢的。
发布于 2021-05-07 23:55:28
matplotlib提供了文本自动换行功能,参见this example或this example。
我不认为您可以使用他的AnnotationBbox
来做这件事,而是使用带有参数wrap=True
的plt.text
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
text = "Test 2 blah blah blah"
xi, yi = 0.2, 0.15
txt = ax.text(xi, yi, text, wrap=True)
# Override the object's method for getting available width
# Note width is in pixels.
txt._get_wrap_line_width = lambda : 70.
# the same but with a box
text = "Iggy Pop blah blah blah blah blah blah blah"
txt = ax.text(.5, .6, text, ha='left', va='top', wrap=True,
bbox=dict(boxstyle='square', fc='w', ec='r'))
txt._get_wrap_line_width = lambda : 60.
https://stackoverflow.com/questions/67442326
复制相似问题