-1

So here is my chart:

enter image description here

The chart was made with 2 different arrays:

[' A6' ' Q2' ' Q5' ' A5' ' A1' ' A4' ' Q3' ' A3']
[ 748  822  877  882 1347 1381 1417 1929]

The first one being an array of strings I believe. Now, I've looked up different solutions to annotate the bars and each of them I was able to find were with pandas dataframe plots. Mine has numpy arrays... I don't know if that should make it more complex or not?

Anyways, here is the code I tried to get the annotations on my chart:

plt.figure()
plot = plt.bar(x, y)
for bar in plot.patches:
    plot.annotate(bar.get_height(),
                  (bar.get_x() + bar.get_width() / 2,
                   bar.get_height()), ha='center', va='center',
                  size=15, xytext=(0, 8),
                  textcoords='offset points')
plt.xlabel("Car Model")
plt.ylabel("Car Frequency")
plt.title("Frequency of Most Popular Audi Cars")
plt.ylim(bottom=0)
plt.show()

This code gives me an error:

Traceback (most recent call last):
  File "blablabla", line 137, in <module>
    plot.annotate(bar.get_height(),
AttributeError: 'BarContainer' object has no attribute 'annotate'

So it seems as though my BarContainer or bars have no attribute annotate... to be frank even after looking it up I have no clue what it means.

Could anyone help with this?

Thanks and sorry if code is missing info, tried to make it complete.

JacobMarlo
  • 87
  • 7
  • Use `matplotlib.pyplot.bar_label`. [Plot and Code](https://i.stack.imgur.com/qbJuG.png) and [Adding value labels on a matplotlib bar chart](https://stackoverflow.com/a/67561982/7758804) – Trenton McKinney Oct 18 '21 at 01:00

1 Answers1

2

I am able to annotate by using axes.pathces instead of plot.patches.

x = [' A6' ,' Q2', ' Q5', ' A5', ' A1', ' A4', ' Q3', ' A3']
y = [ 748,  822,  877,  882 ,1347 ,1381 ,1417, 1929]
fig, ax =  plt.subplots(figsize = (10, 7))
ax.bar(x, y)
for bar in ax.patches:
    ax.annotate(text = bar.get_height(),
                  xy = (bar.get_x() + bar.get_width() / 2, bar.get_height()),
                  ha='center', 
                  va='center',
                  size=15,
                  xytext=(0, 8),
                  textcoords='offset points')
plt.xlabel("Car Model")
plt.ylabel("Car Frequency")
plt.title("Frequency of Most Popular Audi Cars")
plt.ylim(bottom=0)
plt.show()

Output

Ajay Verma
  • 610
  • 2
  • 12