我正在尝试使用 matplotlib 中的 TextArea
和 AnnotationBbox
绘制文本。
我的代码应绘制的结果文本如下所示:
这是我正在使用的代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, TextArea, HPacker, VPacker
fig, ax = plt.subplots(figsize=(12,8))
ybox1 = TextArea("Premier League Standing 2019/20 \n",
textprops=dict(color="k", size=15, ha='center',va='center'))
ybox2 = TextArea("Liverpool",
textprops=dict(color="crimson", size=15,ha='center',va='center'))
ybox3 = TextArea("Man City",
textprops=dict(color="skyblue", size=15,ha='center',va='center'))
ybox4 = TextArea("and",
textprops=dict(color="k", size=15,ha='center',va='center'))
ybox5 = TextArea("Chelsea",
textprops=dict(color="blue", size=15,ha='center',va='center'))
ybox = HPacker(children=[ybox1, ybox2, ybox3, ybox4, ybox5],align="center", pad=0, sep=2)
text = AnnotationBbox(ybox, (0.5, 0.5), frameon=False)
ax.add_artist(text)
plt.show()
我应该在代码中添加/更新/更改什么,以便代码产生所需的结果。
最佳答案
更改了水平对齐方式,删除了第一个框中的换行符,增加了填充,使用了VPacker
。结果:
代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, TextArea, HPacker, VPacker
fig, ax = plt.subplots(figsize=(12,8))
ybox1 = TextArea("Premier League Standing 2019/20",
textprops=dict(color="k", size=15, ha='left',va='baseline'))
ybox2 = TextArea("Liverpool",
textprops=dict(color="crimson", size=15, ha='left',va='baseline'))
ybox3 = TextArea("Man City",
textprops=dict(color="skyblue", size=15, ha='left',va='baseline'))
ybox4 = TextArea("and",
textprops=dict(color="k", size=15, ha='left',va='baseline'))
ybox5 = TextArea("Chelsea",
textprops=dict(color="blue", size=15, ha='left',va='baseline'))
yboxh = HPacker(children=[ybox2, ybox3, ybox4, ybox5], align="left", pad=0, sep=4)
ybox = VPacker(children=[ybox1, yboxh], pad=0, sep=4)
text = AnnotationBbox(ybox, (0.5, 0.5), frameon=False)
ax.add_artist(text)
plt.show()
关于python - 在 matplotlib 中使用 TextArea 和 AnnotationBbox 绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63659519/