首页 > 解决方案 > 在 matplotlib 中使用 TextArea 和 AnnotationBbox 绘制文本

问题描述

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

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

在此处输入图像描述

这是我正在使用的代码:

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

它正在下面的情节中产生 在此处输入图像描述

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

标签: pythonmatplotlib

解决方案


更改了水平对齐方式,删除了第一个框中的换行符,增加了填充,使用了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()

推荐阅读