Andrew Hamel
Andrew Hamel

Reputation: 366

Add labels to grouped seaborn barplot from DIFFERENT COLUMN

I know there are other entries similar to this, but nothing exactly like this.

Suppose I have this dataframe:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({"percentage": [0.3, 0.4, 0.5, 0.2],
                   "xaxis": ["set1", "set1", "set2", "set2"],
                   "hues": ["a", "b", "c", "d"],
                   "number": [1,2,3,4]
                  })

and I create a grouped barplot in Seaborn:

sns.set(style="whitegrid")

fig, ax = plt.subplots(figsize=(10,10))
ax = sns.barplot(data=df,
                 x="xaxis",
                 y="percentage",
                 hue="hues")
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)

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

This nicely adds labels from the "percentage" column.

BUT

How do I label the barplots using the entries from the "number" column? For clarification, I chose the numbers 1,2,3,4 as a toy example. They are not consecutive in my real data.

For reference, I am using Python 3.9.X, Seaborn 0.11.2, and Matplotlib 3.5.0.

I suspect the answer lies somewhere in the container but do not know.

I have also seen potential answers that use this code:

for index, row in df.iterrows():
    ax.text(insert_codehere)

but that did not seem to work for me either.

Thanks in advance.

enter image description here

Upvotes: 0

Views: 3084

Answers (1)

user15398259
user15398259

Reputation:

for container, number in zip(ax.containers, df.number):
    ax.bar_label(container, labels=[number, number])

enter image description here

Upvotes: 2

Related Questions