Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
How to Annotate Bars in Grouped Barplot in Python?
Next article icon

Annotation means adding notes to a diagram stating what values do it represents. It often gets tiresome for the user to read the values from the graph when the graph is scaled down or is overly populated.  In this article, we will discuss how to annotate the bar plots created in python usingmatplotlib library.

Following are examples of annotated and non-annotated bar plots:

annotateautox2-copy
Annotate Bars in Barplot with Matplotlib

Step-by-step Approach:

Python
# Importing necessary librariesimportmatplotlib.pyplotasplt# Example 1: Barplot for Marks Secureddata={"Name":["Alex","Bob","Clarein","Dexter"],"Marks":[45,23,78,65]}names=data["Name"]marks=data["Marks"]df=pd.DataFrame(data)df

Output:

User generated pandas dataframe
  • Let's now start plotting the dataframe using theseaborn library. We get the following results. But it is not quite visible that what are the actual values in the bar plots. This condition can also arise when the values of neighboring plots are quite close to each other.
Python
plt.figure(figsize=(8,6))bars=plt.bar(df['Name'],df['Marks'],color='skyblue')plt.xlabel("Students",fontsize=14)plt.ylabel("Marks Secured",fontsize=14)plt.title("Marks Secured by Students",fontsize=16)plt.show()

Output:

Marks-Secured-by-Students
Bar Plot Without Annotations
  • Adding the annotations. Our strategy here will be to iterate all over the bars and put a text over all of them that will point out the values of that particular bar. Here we will use the Matlpotlib's function calledannotate().We can find various uses of this function in various scenarios, currently, we will be just showing the value of the respective bars at their top.

Our steps will be:

  1. Iterate over the bars
  2. Get the x-axis position(x) and the width(w) of the bar this will help us to get the x coordinate of the text i.e.get_x()+get_width()/2.
  3. The y-coordinate(y) of the text can be found using the height of the bar i.e. get_height()
  4. So we have the coordinates of the annotation value i.e.get_x()+get_width()/2, get_height()
  5. But this will print the annotation exactly on the boundary of the bar so to get a more pleasing annotated plot we use the parameterxyplot=(0, 8). Here 8 denotes the pixels that will be left from the top of the bar. Therefore to go below the barline we can usexy=(0,-8).
  6. So we execute the following code to get the annotated graph:
Python
forbarinbars:plt.text(bar.get_x()+bar.get_width()/2,bar.get_height(),f'{bar.get_height():.2f}',ha='center',va='bottom',fontsize=12)


Below is the complete program based on the above approach:

Python
plt.figure(figsize=(8,6))bars=plt.bar(names,marks,color='orange')# Annotating barsforbarinbars:plt.text(bar.get_x()+bar.get_width()/2,bar.get_height(),f'{bar.get_height():.2f}',ha='center',va='bottom',fontsize=12)# Adding labels and titleplt.xlabel("Students",fontsize=14)plt.ylabel("Marks Secured",fontsize=14)plt.title("Marks Secured by Students",fontsize=16)plt.show()

Output:

Marks-Secured-by-Students-anno
Bar Plot With Annotations

Below are some examples which depict annotate bars in barplot withmatplotlib library:

Example 1:

Python
# Example 2: Barplot for Language Popularitydata={"Language":["Python","C++","Java"],"Students":[75,50,25]}languages=data["Language"]students=data["Students"]plt.figure(figsize=(6,5))bars=plt.bar(languages,students,color='green')# Annotating barsforbarinbars:plt.text(bar.get_x()+bar.get_width()/2,bar.get_height(),f'{bar.get_height():.2f}',ha='center',va='bottom',fontsize=12)# Adding labels and titleplt.xlabel("Programming Language",fontsize=14)plt.ylabel("Number of Students",fontsize=14)plt.title("Programming Language Popularity",fontsize=16)plt.show()

Output:

Programming-Language-Popularity
Bar Plot With Annotations Example 1

Example 2:

Python
# Example 3: Barplot for Sectionsdata={"Section":["A","B","C","D","E"],"Students":[0,10,20,30,40]}sections=data["Section"]students=data["Students"]plt.figure(figsize=(6,5))bars=plt.bar(sections,students,color='salmon')# Annotating barsforbarinbars:plt.text(bar.get_x()+bar.get_width()/2,bar.get_height(),f'{bar.get_height():.2f}',ha='center',va='bottom',fontsize=12)# Adding labels and titleplt.xlabel("Sections",fontsize=14)plt.ylabel("Number of Students",fontsize=14)plt.title("Students in Different Sections",fontsize=16)plt.show()

Output:

Students-in-Different-Sections
Bar Plot With Annotations Example 2



Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp