Skip to content Skip to sidebar Skip to footer

How To Annotate A Pandas Stacked Bar, With More Than 2 Stacks?

I have the following dataset that contains weekly information for 4 different levels. I created a stacked bar chart, each stack representing a level, and each bar a week. How can I

Solution 1:

  • A stacked bar is not going to equal 1 unless the sum of the values in each row are equal to 1.
    • I suggest adding columns to the DataFrame with the "normed" values, then plot that. This will also resolve issues of correctly labeling the stacked bars.
    • In this case, replace df with res = df.div(df.sum(axis=1), axis=0).
  • The labels come from the value in the DataFrame

Imports

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

Data

rng=pd.date_range('2020-01-02', periods=10,freq='7D')
level=['low', 'medium', 'high', 'very_high']
np.random.seed(450)
values=np.random.randint(1, 100, size=(10, 4))
df=pd.DataFrame(index=rng, data=values, columns=level)

# display(df)
            low  medium  high  very_high
2020-01-02   644779432020-01-09   505624712020-01-16446668212020-01-23165277122020-01-3092839142020-02-06   89592582020-02-1330663892020-02-20591593222020-02-27956856472020-03-05   88585920

Horizontal Stacked Bar

plt.style.use('ggplot')

ax = df.plot(stacked=True, kind='barh', figsize=(12, 8))
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
ax.set_yticklabels(labels=df.index.date)

# .patches is everything inside of the chartfor rect in ax.patches:
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()
    
    # The width of the bar is the data value and can used as the label
    label_text = width  # f'{width:.2f}' if you have decimal values as labels
    
    label_x = x + width / 2
    label_y = y + height / 2
    ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)

enter image description here

Vertical Stacked Bar

ax = df.plot(stacked=True, kind='bar', figsize=(12, 8))
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
ax.set_xticklabels(labels=df.index.date)

# .patches is everything inside of the chartfor rect in ax.patches:
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()
    
    # The width of the bar is the data value and can used as the label
    label_text = f'{height}'# f'{height:.2f}' if you have decimal values as labels
    
    label_x = x + width / 2
    label_y = y + height / 2
    ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)

enter image description here

Post a Comment for "How To Annotate A Pandas Stacked Bar, With More Than 2 Stacks?"