简体   繁体   中英

Total label for stacked bar

I have the following code:

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')

I am trying to add total figure as a label on top of each column, but just can't figure it out. i tried multiple examples, and nothing is working so far.

Please help Thank you

By default, the function bar_label() uses the sum of the bar height and its bottom ( .get_y() ) as the number shown on top (only the height for the centered labels). You only want to call this for the last set of bars shown (so ax.containers[-1] ).

Here is an example:

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 堆叠条

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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