Add Data Labels
Add Data Labels
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
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
s String to be displayed.
ha Horizontal alignment.
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
def addlabels(x,y):
for i in range(len(x)):
plt.text(i,y[i],y[i])
if __name__ == '__main__':
plt.bar(x, y)
addlabels(x, y)
plt.title("College Admission")
plt.xlabel("Courses")
plt.ylabel("Number of Admissions")
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
# function to add value labels
def addlabels(x,y):
for i in range(len(x)):
if __name__ == '__main__':
"BSc", "MSc"]
plt.bar(x, y)
addlabels(x, y)
plt.title("College Admission")
plt.xlabel("Courses")
plt.ylabel("Number of Admissions")
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
def addlabels(x,y):
for i in range(len(x)):
if __name__ == '__main__':
plt.figure(figsize = (10,5))
addlabels(x, y)
plt.title("College Admission")
plt.xlabel("Courses")
plt.ylabel("Number of Admissions")
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
def addlabels(x,y):
for i in range(len(x)):
if __name__ == '__main__':
plt.figure(figsize = (10,5))
addlabels(x, y)
plt.title("College Admission")
plt.xlabel("Courses")
plt.ylabel("Number of Admissions")
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
# function to add value labels
def addlabels(x,y):
for i in range(len(x)):
if __name__ == '__main__':
plt.figure(figsize = (10,5))
# making the bar chart on the data with color red
addlabels(x, y)
plt.title("College Admission")
plt.xlabel("Courses")
plt.ylabel("Number of Admissions")
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
Article Contributed By :
srishivansh5404
@srishivansh5404
Vote for difficulty
EasyNormalMediumHardExpert
Article Tags :
Picked
Python-matplotlib
Python
Improve Article
Report Issue
WHAT'S NEW
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Load Comments
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