python - 当条形分组时显示条形的值

标签 python pandas matplotlib data-science data-analysis

虽然 stackoverflow 上有很多关于向单个条形图添加值的答案,但我找不到向分组条形图添加精确值的适当方法。这就是我创建条形图的方式:

labels = ['<20','20-29', '30-39','40-49','50-59','60-69','70-79','80+']
maleAges = (malesUnder20, males20To30, males30To40)
femaleAges = (femalesUnder20, females20To30,males30To40)

# bars = []

def subcategorybar(X, vals, width=0.8):
    n = len(vals)
    _X = np.arange(len(X))
    for i in range(n):
        bar = plt.bar(_X - width/2. + i/float(n)*width, vals[i], 
                width=width/float(n), align="edge")
        bars.append(bar)
    plt.xticks(_X, X)
subcategorybar(labels, [maleAges, femaleAges])

我尝试过使用这个功能

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')      

并从子类别函数中传递了bars,但它给了我一个错误

AttributeError: 'BarContainer' object has no attribute 'get_height'

另一种方法是使用 plt.text 和 plt.annotate,但在这种特殊情况下,我无法找出两者的正确参数。

编辑:

我绘制图表的第二种方法是这样的:

N = 3
labels = ['<20','20-29', '30-39','40-49']
maleAges = (malesUnder20, males20To30, males30To40)
femaleAges = (femalesUnder20, females20To30,males30To40)
ind = np.arange(N) 
width = 0.35  

plt.figure(figsize=(10,5))
plt.bar(ind, maleAges , width, label='Male')
plt.bar(ind + width, femaleAges, width, label='Female')

plt.xticks(ind + width / 2,  ('<20','20-29', '30-39'))

plt.legend(loc='best')
plt.show()

我也尝试在这里使用 plt.annotations 但没有成功。

使用上述两种方法中的任何一种的解决方案可能会有所帮助。注意:我正在寻找编辑现有函数的方法。

最佳答案

您可以直接从 axes 执行此操作补丁:

for p in axes.patches:
    axes.annotate(s=np.round(p.get_height(), decimals=2),
                xy=(p.get_x()+p.get_width()/2., p.get_height()),
                ha='center',
                va='center',
                xytext=(0, 10),
                textcoords='offset points')

对示例的影响:

import numpy as np
import matplotlib.pyplot as plt

N = 3
labels = ['<20','20-29', '30-39','40-49']
maleAges = (1, 2, 3)
femaleAges = (1, 3, 4)
ind = np.arange(N) 
width = 0.35  

figure, axes = plt.subplots()

plt.bar(ind, maleAges , width, label='Male')
plt.bar(ind + width, femaleAges, width, label='Female')

plt.xticks(ind + width / 2,  ('<20','20-29', '30-39'))

for p in axes.patches:
    axes.annotate(s=np.round(p.get_height(), decimals=2),
                xy=(p.get_x()+p.get_width()/2., p.get_height()),
                ha='center',
                va='center',
                xytext=(0, 10),
                textcoords='offset points')

plt.legend(loc='best')
plt.show()

enter image description here

关于python - 当条形分组时显示条形的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63220286/

相关文章:

python - 计算python中的逐行时间差

python - 重复数组的每个值两次(numpy)

Python unittest 没有运行指定的测试

python - python swig 中的 repr 函数

python - 如何将 NaN >> ['' ] 转换为 Pandas Dataframe 的所有元素?

pandas - Pyarrow 用于 Parquet 文件,还是只是 Pandas ?

python - RuntimeError : the sip module implements API v11. 0 到 v11.2 但 PyQt5.QtCore 模块需要 API v11.3

python - Jupyter 中的 Matplotlib 内联 - 如何控制绘图的显示时间?

python - 使用 Seaborn 的 FacetGrid 自定义注释

python - 线性回归 Lasagne/Theano