0

I have two overlaid bar plots from binary column data. I need to add the value_counts number as label to each bar of the plot.

df = pd.DataFrame({'y_pred': y_pred, 'y_test': y_test})
df.y_test.value_counts().plot(kind='bar')
df.y_pred.value_counts().plot(kind='bar', width=0.3, color='r')
plt.legend()
plt.show()

bar plot

In another question I found:

for p in ax.patches:
        ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))

but I did not understand how this would loop through the bars in my case. Copy paste obviously did not work. the code with 'for loop' was executed without error messages but still showed the same plot without labels...

plot

df = pd.DataFrame({'y_pred': y_pred, 'y_test': y_test})
df.y_test.value_counts().plot(kind='bar')
df.y_pred.value_counts().plot(kind='bar', width=0.3, color='r')
for p in ax.patches:
    ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))

plt.legend()

plt.show()
Sebban
  • 15
  • 4
  • I tried this method (as you can see in the edit) it just gave me the same plot without anotations or error message (labels do now show somehow) – Sebban Jul 05 '19 at 12:32

1 Answers1

0

You need to pass ax into the plot command:

fig, ax = plt.subplots()
df.y_test.value_counts().plot(kind='bar', ax=ax)
df.y_pred.value_counts().plot(kind='bar', width=0.3, color='r', ax=ax)
for p in ax.patches:
    ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))

plt.legend()

plt.show()

Output:

enter image description here

Play with get_width a little to align the labels.

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74