0

I want to write custom values above my bars in barplot which I made using sns.barplot. My custom values are available in the same DataFrame under another column. This question has been answered elsewhere however, they do not consider Hue. How would you write custom values sourced in the same DataFrame when Hue is defined?

DataFrame:

XData YData Type Label
X 123 TypeA 001
Y 234 TypeA 010
X 345 TypeB 100
Y 567 TypeB 000

here is my plot:

MyBarPlot = sns.barplot(data=DataFrame, x="XData", y="YData",hue="Type",width=0.8, errorbar=('ci', 95))


DataFrameGrouped = DataFrame.groupby(['XData','YData']).label.mean()


for container in MyBarPlot .containers:
 MyBarPlot.bar_label(container[0], labels=DataFrameGrouped, padding=3, fmt='%.1f')

1 Answers1

0

Given the DataFrame and seaborn plot you shared, the error might be stemming from the attempt to use 'label' from the DataFrameGrouped directly, which is not defined as a 'label' attribute for the grouped object. The arrangement is the problem here as it can be a big issue when using hue.

MyBarPlot = sns.barplot(data=df, x="XData", y="YData", hue="Type", width=0.8)
plt.ylim(0, df['YData'].max() + 100)  # This is to make sure there is enough space for labels above the bars

# Create a nested dictionary from the DataFrame for easy label access
label_dict = df.set_index(['XData', 'Type'])['Label'].to_dict()

for i, bar in enumerate(MyBarPlot.patches):
    # Calculate the label position
    height = bar.get_height()
    x = bar.get_x() + bar.get_width() / 2
    y = height

    # Get the corresponding label for this bar from label_dict
    label = label_dict[(df['XData'].unique()[i // 2], df['Type'].unique()[i % 2])]

    # Add the label to the bar
    plt.text(x, y, label, ha='center', va='bottom')

plt.show()

I have attached a collab sheet with the results. https://colab.research.google.com/drive/1Ipt3FS5WkDjDc0uVm9RSgtgeI4uSFlUC?usp=sharing