繁体   English   中英

堆叠条总 label

[英]Total label for stacked bar

我有以下代码:

fig, ax = plt.subplots()
single_customer_g['Size_GB'] = round(single_customer_g['Size_GB'] / 1024, 2)
single_customer_g = single_customer_g.pivot('Date', 'Vault', 'Size_GB')
single_customer_g.plot.bar(stacked=True, rot=1, figsize=(15, 10), ax=ax, zorder=3)

for c in ax.containers:
    labels = [round(v.get_height(), 2) if v.get_height() > 0 else 0 for v in c]
    ax.bar_label(c, labels=labels, label_type='center')

我正在尝试在每列的顶部添加总数字作为 label,但无法弄清楚。 我尝试了多个示例,但到目前为止没有任何效果。

请帮忙谢谢

默认情况下,function bar_label()使用条形高度及其底部的总和 ( .get_y() ) 作为顶部显示的数字(仅居中标签的高度)。 您只想为显示的最后一组条形图调用它(因此ax.containers[-1] )。

这是一个例子:

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({'Date': np.tile(pd.date_range('20211201', freq='D', periods=10), 5),
                   'Vault': np.repeat([*'abcde'], 10),
                   'Size_GB': np.random.uniform(0, 3, 50)})
df_pivoted = df.pivot('Date', 'Vault', 'Size_GB')
ax = df_pivoted.plot.bar(stacked=True, figsize=(12, 5))
ax.set_xticklabels([d.strftime('%b %d\n%Y') for d in df_pivoted.index], rotation=0)
ax.bar_label(ax.containers[-1], fmt='%.2f') # default on top
for bars in ax.containers:
    labels = [f"{bar.get_height():.2f}" if bar.get_height() > 0.2 else '' for bar in bars]
    ax.bar_label(bars, labels=labels, label_type='center', color='white')
ax.set_xlabel('')
plt.tight_layout()
plt.show()

带有总标签的 pandas 堆叠条

暂无
暂无

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

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