繁体   English   中英

Matplotlib 在子图中的条形图上打印值

[英]Matplotlib print values on bars in subplots

使用上面的代码,我创建了 5 个五个子图:

values = {"x_values" : ["ENN", "CNN", "ENN-CNN"],
"eu" : [11, 79.97, 91],
"man" : [11, 80, 90],
"min3" : [11, 79.70, 90],
"min4" : [11, 79.50, 90],
"che" : [12, 78, 89]}

df = pd.DataFrame(data=values)

fig, axs = plt.subplots(2, 3, figsize=(10,6))

eu = axs[0, 0].bar(df["x_values"], df["eu"]
man = axs[0, 1].bar(df["x_values"], df["man"])
min3 = axs[0, 2].bar(df["x_values"], df["min3"])
min4 = axs[1, 0].bar(df["x_values"], df["min4"])
che = axs[1, 1].bar(df["x_values"], df["che"])
fig.delaxes(axs[1, 2])

他们按应有的方式打印,但我还想将每个条形图的 y 值添加到条形图。 就像图片中一样在这里输入图片描述

我已经尝试了下面的代码,但它没有打印任何东西,没有错误但也没有打印

for index, value in enumerate(df["corresponding_df"]):
    plt.text(value, index, str(value))

如果我尝试variable-name.text(value, index, str(value))我得到错误'BarContainer' object has no attribute 'text' 如果fig.text再次不打印。 如果axs[subplot-index].text我只能在地块外的 window 末尾看到一个数字。 有什么建议吗?

在 matplotlib 3.4.0+ 中使用 bar_label 试试这个:

values = {"x_values" : ["ENN", "CNN", "ENN-CNN"],
"eu" : [11, 79.97, 91],
"man" : [11, 80, 90],
"min3" : [11, 79.70, 90],
"min4" : [11, 79.50, 90],
"che" : [12, 78, 89]}

df = pd.DataFrame(data=values)

fig, axs = plt.subplots(2, 3, figsize=(10,6))

eu = axs[0, 0].bar(df["x_values"], df["eu"])
axs[0,0].bar_label(eu)
man = axs[0, 1].bar(df["x_values"], df["man"])
axs[0,1].bar_label(man)
min3 = axs[0, 2].bar(df["x_values"], df["min3"])
axs[0,2].bar_label(min3)
min4 = axs[1, 0].bar(df["x_values"], df["min4"])
axs[1,0].bar_label(min4)
che = axs[1, 1].bar(df["x_values"], df["che"])
axs[1,1].bar_label(che)
fig.delaxes(axs[1, 2])

Output:

在此处输入图像描述

对于文本,可以这样做:

for ax in axs.flatten():
    for bar in ax.patches:
        ax.text(bar.get_x() + bar.get_width() / 2, 
                bar.get_height()-7,
                bar.get_height(), 
                ha='center',
                color='w')

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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