【问题标题】:Question regarding adding bar labels to grouped bar chart using matplotlib关于使用 matplotlib 将条形标签添加到分组条形图的问题
【发布时间】:2021-06-19 18:57:11
【问题描述】:

我正在使用 matplotlib 绘制分组条形图。我想在每个栏的顶部添加 labelsz 和 labelsJ。这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
labels = ['X1', 'X2', 'X3']
betaz = [0.5, 0.6, 0.4]
labelsz = ['***','***','**']

betaJ = [-0.8, -0.9, -0.2]
labelsJ = ['***','***','***']

x = np.arange(len(labels))
width = 0.35 

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, betaz, width, label=r'$\beta_z$', color='navy')
rects2 = ax.bar(x + width/2, betaJ, width, label=r'$\beta_{JOE}$', color='gray')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

plt.xticks(rotation=90)

fig.tight_layout()

plt.show()

我尝试使用 ax.bar_label(labelsz) 和 ax.bar_label(labelsJ) 但我不断收到 AttributeError: 'list' object has no attribute 'patches'。我对 matplotlib 很陌生,任何帮助都将不胜感激。

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:
    fig, ax = plt.subplots()
    rects1 = ax.bar(x - width/2, betaz, width, label=r'$\beta_z$', color='navy')
    rects2 = ax.bar(x + width/2, betaJ, width, label=r'$\beta_{JOE}$', color='gray')
    ax.bar_label(rects1, labelsz,label_type='edge')
    ax.bar_label(rects2, labelsJ,label_type='edge')
    

    ax.bar_label 是这样写的

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 2021-02-20
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 2015-05-09
      相关资源
      最近更新 更多