python - 在 matplotlib 中使用 TextArea 和 AnnotationBbox 绘制文本

标签 python matplotlib

我正在尝试使用 matplotlib 中的 TextAreaAnnotationBbox 绘制文本。

我的代码应绘制的结果文本如下所示:

enter image description here

这是我正在使用的代码:

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()

它正在生成下面的图 enter image description here

我应该在代码中添加/更新/更改什么,以便代码产生所需的结果。

最佳答案

更改了水平对齐方式,删除了第一个框中的换行符,增加了填充,使用了VPacker。结果:

HPacker

代码:

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/

相关文章:

Python 将列表的第一个元素与其余元素一起压缩

python - 在 matplotlib 子图中显示具有实际大小的不同图像

python - 如何在Python中绘制耦合非线性二阶ODE的二阶导数?

python - 绘制 numpy.histogram2d()

python - 在集合字典中将具有相同值的所有键分组

python - 使用 pip 和 virtualenv 的 scipy 安装以错误和 g++ 退出状态 4 结束

python - Django 多选字段 : Make some choices readonly when editing

python - Python IDLE 的默认工作目录?

python - 在线图中用标记突出显示单个点

python - 当时间数据已作为索引确定时,如何绘制时间相关数据?