简体   繁体   中英

How to add values on bar chart in python

I made a bar chart in Python but I cannot add the values on each of the bar. Does anyone know how to do it?

yelp_area=df.groupby('Area').Yelp_rating.mean()

yelp_area.plot(kind='bar', rot=0, alpha=0.8, figsize=(10,6), color='r')

plt.xticks(rotation='vertical')

plt.ylabel('Average Rating on a 1-5 scale')

I attached the picture of the bar chart.

You can use addlabels in it:

# importing library
import matplotlib.pyplot as plt
  
# function to add value labels
def addlabels(x,y):
    for i in range(len(x)):
        plt.text(i, y[i]//2,y[i], ha = 'center',
                 Bbox = dict(facecolor = 'white', alpha = .5))
  
if __name__ == '__main__':
    
    # creating data on which bar chart will be plot
    x = ["Engineering", "Hotel Managment", "MBA",
         "Mass Communication", "BBA", "BSc", "MSc"]
    y = [9330, 4050, 3030, 5500,
         8040, 4560, 6650]
      
    # setting figure size by using figure() function 
    plt.figure(figsize = (10,5))
    
    # making the bar chart on the data with color red
    plt.bar(x, y, color = 'red')
      
    # calling the function to add value labels
    addlabels(x, y)
      
    # giving title to the plot
    plt.title("College Admission")
      
    # giving X and Y labels
    plt.xlabel("Courses")
    plt.ylabel("Number of Admissions")
      
    # visualizing the plot
    plt.show()

Which gives you this result.- Attached Image.

You can refer here for more detailed information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM