0% found this document useful (0 votes)
44 views

Add Data Labels

Uploaded by

murtaza mannan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Add Data Labels

Uploaded by

murtaza mannan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Skip to content

 Tutorials
 Student
 Jobs
 Courses

Write
Come write articles for us and get featured

Practice
Learn and code with the best industry experts

Premium
Get access to ad-free content, doubt assistance and more!

Jobs
Come and find your dream job with us

o Geeks Digest
o Quizzes
o Geeks Campus
o Gblog Articles
o IDE
o Campus Mantri

 Sign In
 Sign In
 Home
 Saved Videos
 Courses

o Practice DS & Algo.
o Algorithms
o Analysis of Algorithms
o Data Structures
o Interview Corner
o Languages
o CS Subjects
o GATE
o Web Technologies
o Software Designs
o School Learning
o Mathematics
o Maths Notes (Class 8-11)
o NCERT Solutions
o RD Sharma Solutions
o ISRO CS
o UGC NET CS
o Student
o Jobs
 GBlog
 Puzzles
 What's New ?
 Change Language
Related Articles

Related Articles
 How to display the value of each bar in a bar chart using Matplotlib?
 Adding value labels on a Matplotlib Bar Chart
 Matplotlib.pyplot.xticks() in Python
 Python | Matplotlib.pyplot ticks
 Decimal Functions in Python | Set 2 (logical_and(), normalize(), quantize(),
rotate() … )
 NetworkX : Python software package for study of complex networks
 Directed Graphs, Multigraphs and Visualization in Networkx
 Python | Visualize graphs generated in NetworkX using Matplotlib
 Visualize Graphs in Python
 Graph Plotting in Python | Set 1
 Graph Plotting in Python | Set 2
 Graph Plotting in Python | Set 3
 Plotting graph using Seaborn | Python
 Box plot visualization with Pandas and Seaborn
 Box Plot in Python using Matplotlib
 How to get column names in Pandas dataframe
 Python program to find number of days between two given dates
 Python | Difference between two dates (in minutes) using datetime.timedelta()
method
 Python | datetime.timedelta() function
 Comparing dates in Python
 Python | Convert string to DateTime and vice-versa
 Convert the column type from string to datetime format in Pandas dataframe
 Adding new column to existing DataFrame in Pandas
 Create a new column in Pandas DataFrame based on the existing columns
 Python | Creating a Pandas dataframe column based on a given condition
 Python map() function
 Taking input in Python
 Python program to convert a list to string

Adding value labels on a Matplotlib Bar


Chart
 Last Updated : 26 Mar, 2021

Prerequisites: Matplotlib
In this article, we are going to Add value labels on a Matplotlib Bar Chart. Bar
Chart is the graphical display of data using bars of different heights.  We can
compare different data’s using this bar chart. For plotting the data in Python we
use bar() function provided by Matplotlib Library in this we can pass our data as a
parameter to visualize, but the default chart is drawn on the given data doesn’t
contain any value labels on each bar of the bar chart, since the default bar chart
doesn’t contain any value label of each bar of the bar chart it is difficult to analyze
the exact value represented by the individual bars of the bar chart.
 Attention geek! Strengthen your foundations with the Python Programming
Foundation Course and learn the basics.  
To begin with, your interview preparations Enhance your Data Structures concepts
with the Python DS Course. And to begin with your Machine Learning Journey,
join the Machine Learning - Basic Level Course
For Plotting the bar chart with value labels we are using mainly two methods
provided by Matplotlib Library.
 For making the Bar Chart
Syntax: plt.bar(x, height, color)
 For adding text on the Bar Chart
Syntax: plt.text(x, y, s, ha, Bbox)
We are showing some parameters which are used in this article:

Paramete Description
r

x Data values plot on X-axis of the plot.

height  Data values plot on Y-axis of the plot.

color Set the color of the plot.

x, y  coordinates of the plot.

s String to be displayed.

ha Horizontal alignment.

Bbox Put the rectangular box around the text.

Steps Needed:
 Import the library.
 Create the function which can add the value labels by taking x and y as a
parameter, now in the function, we will run the for loop for the length of
the x value we can find the length by using the len() function, and in that
passed variable whose length we want.
 Now use plt.text() function to add value labels to the bar chart in this pass
the x and y coordinates which will be i and y[i] which is nothing but the
height of the bar and pass y[i] this represents the string which will be
displayed on the given co-ordinates i.e, i and y[i].
 For adding the value labels in the center of the height of the bar just we
have to divide the y co-ordinates by 2 i.e, y[i]//2 by doing this we will get
the center coordinates of each bar as soon as the for loop runs for each
value of i.
 With this, we can also set the parameter ha and Bbox that are horizontal
alignment which aligns the value labels at the center of the bar when we
pass ha=center and Bbox which display the value labels in the covered
rectangular box for this we have to create a dictionary using dict() and in
this pass the facecolor that is color we want and alpha if we want the
opacity we can set.
 Now after creating the function we have to create main function from
where the program starts to run.
 Create or import the data for which bar chart is plotted.
 Give the figure size so that the values and labels of the plot clearly visible
and cannot be overlapping you can set accordingly by
using plt.figure() function in which pass the figsize as a parameter.
 Now plot the bar chart using plt.bar() function in which pass the data
values and color accordingly if you want or the default color will be
displayed.
 Now after making the bar chart call the function which we had created
for adding value labels.
 Set the title, X-axis labels and Y-axis labels of the chart/plot.
 Now visualize the plot by using plt.show() function.
Example 1: Adding value labels on the Bar Chart at the default setting.
 Python

# 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],y[i])

  

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]

      

    # making the bar chart on the data

    plt.bar(x, y)

      

    # 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()

Output:
The above plot is plotted on the default settings, from the above figure we can
observe that the value labels for each bar is added on the top, but they are present
slightly on the right side of the top of the bar and on the X axis some names of
courses are overlapping.
Example 2: Adding value labels in the center of each Bar on the Bar Chart.
 Python

# 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], y[i], ha = 'center')

  

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

    plt.bar(x, y)
      

    # 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()

Output:
In the above plot, we can observe that the value labels are aligned at the center top
of each bar and on the X-axis the name of the courses which are overlapping are
also shown separately.
For aligning the value labels in the center we had passed only one parameter in the
plt.text() function which is “ha=’center” that is the horizontal alignment of the
text, and for showing the names of the courses separately we had added plt.figure()
function before making the bar chart in which we had passed the figure size as a
parameter and rest of the code is same.
Example 3: Adding value labels by putting them in a rectangular box.
 Python

# 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], y[i], ha = 'center',

                 Bbox = dict(facecolor = 'red', alpha =.8))

  

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


    plt.bar(x, y)

      

    # 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()

Output:
In the above example, we had added the value label which is covered in the
rectangular box, for this in the plt.text() function we have to pass the parameter
Bbox in which we have to create the dictionary and in that dictionary, we can give
facecolor of our choice and alpha which gives the opacity to the box which we can
set accordingly.
Example 4: Adding value labels at the center of the height of each bar of the
Bar Chart.
 Python

# 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')

  

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


    plt.bar(x, y)

      

    # 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()

Output:
In the above example for adding the value label in the center of the height of each
bar, we had just divided the y coordinates by 2 in the plt.text() function inside the
for a loop.
Example 5: Adding the value labels covered in rectangular box at the center
of the height of each bar of Bar Chart.
 Python

# 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()

Output:
In the above example, we had done the same thing as we had done in example 3
but the only difference is we had divided the coordinates of y by 2 so that the
value labels should be displayed at the center of the height of the bar and also we
had changed the color of the bar chart to red by passing the color parameter in the
plt.bar() function.

Like0
Previous
How to display the value of each bar in a bar chart using
Matplotlib?
Next
Matplotlib.pyplot.xticks() in Python
RECOMMENDED ARTICLES
Page :

1
2
3
How to display the value of each bar in a bar chart using Matplotlib?
01, Jan 21

Highlight a Bar in Bar Chart using Altair in Python


08, Nov 20

Adding labels to histogram bars in Matplotlib


23, Feb 21

PyQt5 - Adding border to Bar of Progress Bar


02, Apr 20

Plot Multiple Columns of Pandas Dataframe on Bar Chart with Matplotlib


22, Jan 21

Display percentage above bar chart in Matplotlib


15, Mar 21

Draw a horizontal bar chart with Matplotlib


16, Dec 20

Setting Different error bar colors in bar plot in Matplotlib


02, Jan 21

How to add percentage or count labels above percentage bar plot


in R?
14, Jul 21

How to Add Labels Over Each Bar in Barplot in R?


02, Oct 21
Adding Labels to Method and Functions in Java
26, Oct 20

Adding labels to points plotted on world map in R


16, Jun 21

Adding labels to a Bokeh plot


23, Feb 21

Radar Chart or Spider Chart in Excel


20, May 21

How to change the size of axis labels in Matplotlib?


02, Jan 21

How to Set Tick Labels Font Size in Matplotlib?


24, Nov 20

How To Adjust Position of Axis Labels in Matplotlib?


10, Dec 20

How to Hide Axis Text Ticks or Tick Labels in Matplotlib?


16, Dec 20

Matplotlib - Setting Ticks and Tick Labels


25, Dec 20
Rotation of colorbar tick labels in Matplotlib
21, Jan 21

Rotate axis tick labels in Seaborn and Matplotlib


23, Feb 21

Bar Chart in Pygal


26, Jun 20

Stacked Bar chart in pygal


26, Jun 20

Bar chart using Plotly in Python


02, Jul 20

Article Contributed By :
srishivansh5404
@srishivansh5404
Vote for difficulty
EasyNormalMediumHardExpert
Article Tags :
 Picked
 Python-matplotlib
 Python
Improve Article
Report Issue

WHAT'S NEW

Competitive Programming Live Classes for Students


View Details

DSA Self Paced Course


View Details

DSA Live Classes for Working Professionals


View Details

MOST POPULAR IN PYTHON


 Read JSON file using Python
 Python Dictionary
 Reading and Writing to text files in Python
 Read a file line by line in Python
 Iterate over a list in Python

MORE RELATED ARTICLES IN PYTHON


 Python String | replace()
 sum() function in Python
 How to Install PIP on Windows ?
 Print lists in Python (4 Different Ways)
 Python | Get a list as input from user

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org

 Company
 About Us
 Careers
 Privacy Policy
 Contact Us
 Copyright Policy
 Learn
 Algorithms
 Data Structures
 Languages
 CS Subjects
 Video Tutorials
 Web Development
 Web Tutorials
 HTML
 CSS
 JavaScript
 Bootstrap
 Contribute
 Write an Article
 Write Interview Experience
 Internships
 Videos
@geeksforgeeks , Some rights reserved

You might also like