How to annotate grouped bars from a different column

48 views Asked by At

I am trying to use the new enhanced ax.container and ax.bar methods to annotate a side-by-side stacked bar chart where parameter 'hue' is used, but I want to annotate with another value from the table, not the value that was used to plot with in x and y parameters..

Let me take you through my journey:

Option 1: Working well - Single bar plot, annotated with another column from the table, not the column that was plotted

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

df = sns.load_dataset('tips')
groupedvalues = df.groupby('day').sum(numeric_only=True).reset_index()

g = sns.barplot(x='day', y='tip', data=groupedvalues)

for container in g.containers:
    g.bar_label(container, labels=groupedvalues['total_bill'])

plt.show()

The following plot is produced

single bar chart annotated with another column

This is very clever already, except I want to use 'hue' and stack.

Option 2: Working well - stacked bar plot, it's working when annotated with the height of the bar

from matplotlib import pyplot as plt
import numpy as np

df = sns.load_dataset('tips')
groupedvalues = df.groupby(['day', 'sex']).sum(numeric_only=True).reset_index()

ax = sns.barplot(x='day', y='tip', data=groupedvalues, hue='sex')

for container in ax.containers:  
    ax.bar_label(container)
    
plt.show()

The following image is produced

stacked bar chart annotated with column that was plotted

Option 3: Not working - Stacked bar, not working when I want to annotate with another column from the table, like in option 1

from matplotlib import pyplot as plt
import numpy as np

df = sns.load_dataset('tips')
groupedvalues = df.groupby(['day', 'sex']).sum(numeric_only=True).reset_index()

ax = sns.barplot(x='day', y='tip', data=groupedvalues, hue='sex')

for container in ax.containers:  
    ax.bar_label(container, labels=groupedvalues['total_bill'])    
    
plt.show()

I get the following error AttributeError: 'NoneType' object has no attribute 'get_bbox'

0

There are 0 answers