0

I want to show the percentage on the bar graph from the code below, how do I do it?

results = pd.Series([accu_dt , accu_svm, accu_rf, accu_lg, accu_knn, accu_nb  ])
names = ['Decision Tree','SVm','Random Forest','Logistic Regression','KNN','Naive Bayes']
ax = results.plot(kind = 'bar',figsize=(13,7),color=['black','gray','brown','blue','pink','green'])
ax.set_title('Comparision of Models',fontsize=15)
ax.set_yticks([0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])
ax.set_xticklabels(names ,fontsize=15,rotation = 45)
ax.set_xlabel("Models",fontsize=15)
ax.set_ylabel("Accuracy",fontsize=15)
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • From "on the bar graph" you mean that you want the value of each bar above? – Shayan Feb 22 '22 at 14:14
  • Thank you for your answer. But I was just wanted percentage on top of the bar graph. – The Legend Feb 22 '22 at 16:18
  • It's much better to use official tools. You can use `bar_label`. Read [official doc](https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_label_demo.html) for further information. – Shayan Feb 22 '22 at 16:52
  • 1
    Does this answer your question? [Adding value labels on a matplotlib bar chart](https://stackoverflow.com/questions/28931224/adding-value-labels-on-a-matplotlib-bar-chart) – Shayan Feb 22 '22 at 16:55

1 Answers1

1

Is this your expected output?

Sample Plot

If so, credit to Chris Adams for his answer.

I predefined the values for accu_dt , accu_svm, accu_rf, accu_lg, accu_knn, accu_nb as such:

accu_dt   = [0.90,0.92,0.91,0.95,0.99,0.95,0.90]
accu_svm  = [0.89,0.92,0.95,0.98,0.97,0.89,0.95]
accu_rf   = [0.98,0.99,0.97,0.96,0.98,0.99,0.95]
accu_lg   = [0.79,0.77,0.90,0.85,0.83,0.80,0.78]
accu_knn  = [0.85,0.85,0.84,0.89,0.83,0.81,0.80]
accu_nb   = [0.85,0.84,0.83,0.81,0.85,0.85,0.85]

I didn't change much of your code except the width = 0.7 and the figsize=(30,7) to make the numbers more readable. Noticed that I added loop at the bottom of your code

ax = results.plot(kind = 'bar',figsize=(30,7),color=['black','gray','brown','blue','pink','green'],width = 0.7)
ax.set_title('Comparision of Models',fontsize=15)
ax.set_yticks([0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])
ax.set_xticklabels(names ,fontsize=15,rotation = 45)
ax.set_xlabel("Models",fontsize=15)
ax.set_ylabel("Accuracy",fontsize=15)

# Newly Added Loop
for p in ax.patches:
    width = p.get_width()
    height = p.get_height()
    x, y = p.get_xy() 
    ax.annotate(f'{height:.0%}', (x + width/2, y + height*1.02), ha='center')

Basically what the code does in simple term:

  1. Getting the heights, width and (x,y) coordinate of the bars
  2. Set the annotation at designated (x,y) coordinate
  3. Set the VALUE of the annotation equals the height of the bar (the '.0%' means percentage with zero decimal place)