I want to create a bar graph that identifies the number of observations (n) for each bar in my plot.
I have a data frame that looks like this:
Treatment | Condition | %_time |
---|---|---|
STZ | Stressed | 3 |
Control | Stressed | 6 |
STZ | Unstressed | 2 |
Control | Unstressed | 8 |
I have successfully created a bar plot with the following code and output:
color = (sns.color_palette("Paired"))
sns.set_style(style='white')
fig, ax = plt.subplots(figsize=(9,6))
ax = sns.barplot(x='Treatment',y='% _time_open_arm', hue = 'Condition', data = df,
capsize= .1, palette=color)
plt.legend(title='Groups', loc='upper right')
plt.xlabel("Treatment")
plt.ylabel("% Time in Open Arm")
plt.title("Stress in STZ vs Vehicle ", size=14)
I want to add the n value for each bar inside of each bar. Using the answer from this question, I created a bar plot that displays the n value for each group above its corresponding bar:
ax = sns.countplot(x='Treatment', hue='Condition', data=df)
for container in ax.containers:
ax.bar_label(container)
However, I want the n values displayed on my original barplot so I tried this:
color = (sns.color_palette("Paired"))
sns.set_style(style='white')
fig, ax = plt.subplots(figsize=(9,6))
ax = sns.barplot(x='Treatment',y='% _time_open_arm', hue = 'Condition', data = df,
capsize= .1, palette=color)
plt.legend(title='Groups', loc='upper right')
plt.xlabel("Treatment")
plt.ylabel("% Time in Open Arm")
plt.title("Stress in STZ vs Vehicle ", size=14)
for container in ax.containers:
ax.bar_label(container)
I understand that what I tried is slightly different as I did not use .countplot like the suggested answer in my link. However, whenever I use .countplot, my y axis is automatically converted into "counts" instead of the column I originally wanted to use (%_time). What can I do to get the n values from my second plot to appear on my first plot? Additionally, how can I get these values to appear inside of each bar instead of on top?