【问题标题】:Matplotlib print values on bars in subplotsMatplotlib 在子图中的条形图上打印值
【发布时间】:2022-11-17 04:05:17
【问题描述】:

使用上面的代码,我创建了 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 值添加到条形图。就像图片中一样 enter image description here

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

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,我只能在窗口末尾的地块外看到一个数字。有什么建议吗?

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    在 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])
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2015-05-09
      • 2018-08-22
      相关资源
      最近更新 更多