Matplotlib bar chart labels

In this Python tutorial, we will discuss Matplotlib bar chart labels in python. Here we will cover different examples related to bar chart labels using matplotlib. And we will also cover the following topics:

  • Matplotlib bar chart labels
  • Matplotlib bar chart x-axis labels
  • Matplotlib bar chart y-axis labels
  • Matplotlib bar chart tick labels
  • Matplotlib bar chart label value
  • Matplotlib bar chart with string labels
  • Matplotlib bar chart labels vertical
  • Matplotlib horizontal bar chart labels
  • Matplotlib bar chart x-axis labels horizontal
  • Matplotlib bar chart label rotation
  • Matplotlib bar chart label font size
  • Matplotlib bar chart text labels
  • Matplotlib grouped bar chart with labels
  • Matplotlib bar chart labels overlap
  • Matplotlib bar chart diagonal tick labels
  • Matplotlib stacked bar chart with labels

If you are new to Matplotlib, check out What is Matplotlib and how to use it in Python and also, How to install matplotlib python

Matplotlib bar chart labels

In this section, we are going to learn about matplotlib bar chart labels. Before starting the topic firstly, we have to understand what does “labels” mean.

The label is the phrase or name of the bars in a bar chart.

The following steps are used to add labels to the bar chart are outlined below:

  • Defining Libraries: Import the important libraries which are required to add text in the plot (For data creation and manipulation: Numpy, For data visualization: pyplot from matplotlib).
  • Define X and Y: Define the data values used for the x-axis and y-axis.
  • Plot Bar chart: By using the bar() method plot bar chart.
  • Add label: By using the text(), xlabels(), ylabels(), etc functions we can easily add labels to a bar chart.
  • Display: To show the graph we use the show() function.

Matplotlib bar chart x-axis labels

Matplotlib provides us the functionality to add labels on the x-axis of the plot. Here firstly you know about how to plot bar charts and the labels define what does x-axis represents to us.

By using the xlabels() method you can easily add labels on the axis.

The syntax to plot bar chart and define labels on the x-axis are as follow:

# Plot bar chart
matplotlib.pyplot.bar(x, height)
# Define x-axis labels
matplotlib.pyplot.xlabels()

The parameters defined above are outlined as below:

  • x: specifies x-coordinates of the bar.
  • height: specifies y-coordinates of the bar.

Let’s see an example of x-axis labels on the bar chart:

# Import Library

import matplotlib.pyplot as plt

# Define Data

student = [3,2,0,5,9,1]
weight = [30,35,40,45,50,55]

# Plot Graph
  
plt.bar(weight,student) 

# Define x-axis label

plt.xlabel("Weight of the students")

# Display Graph

plt.show()
  • In the above example, we import matplotlib.pyplot library and after that, we define x coordinates and y coordinates.
  • plt.bar() method is used to plot a bar chart and plt.xlabels() method defines what does x-axis represent.
  • At last, we use plt.show() to visualize the bar chart.
matplotlib bar chart x-axis labels
plt.xlabels() “Labels on x-axis”

Read: Matplotlib plot error bars

Matplotlib bar chart y-axis labels

In this section, we learn to add labels on the y-axis of the plot.

By using the ylabels() method we can easily add labels on the axis.

The syntax to define labels on the y-axis are as follow:

# Y-axis label
matplotlib.pyplot.ylabels()

Let’s see an example to add labels on the y-axis:

# Import Library

import matplotlib.pyplot as plt

# Define Data

student = [3,2,0,5,9,1]
weight = [30,35,40,45,50,55]

# Plot Graph
  
plt.bar(weight,student) 

# Define y-axis label

plt.ylabel("No.of students")

# Display Graph

plt.show()

Here we use the bar() method to plot the bar chart and the ylabel() method to define the y-axis labels.

matplotlib bar chart y-axis labels
plt.ylabels() “Labels on Y-axis”

Read: Matplotlib remove tick labels

Matplotlib bar chart tick labels

Firstly we have to understand what does tick labels mean. Basically, ticks are the markers and labels is the name given to them.

Or we can say that ticks are the markers that represent data points on the axes.

The syntax to add tick labels are as below:

# x-axis tick labels
matplotlib.axes.Axes.set_xticklabels(self,xlabel,fontdict=None,labelpad=None)

The above-used parameters are as follow:

  • xlabel: specifies the label text.
  • fontdict: specifies a dictionary of font styles.
  • labelpad: specifies the spacing in points.

Let’s see an example to set tick labels:

# Import Library

import matplotlib.pyplot as plt

# Define Data

x = [1, 2, 3, 4]
ax1 = plt.subplot()
ax1.set_xticks(x)
ax1.set_yticks(x)

# plot bar chart

plt.bar(x,[2,3,4,12])

# Define tick labels

ax1.set_xticklabels(["A","B","C","D"]) 
ax1.set_yticklabels([1, 2, 3, 4])

# Display graph


plt.show()
  • In the above example, we list the x that defines the tick used in the axes.
  • After this, we use the subplot()method to get the axis of the figure.
  • Then we use the set_xticks() and set_yticks() method to set the ticks on X-axis and Y-axis.
  • set_xticklabels() and set_yticklabels() method is used to set the tick labels of your choice.
  • To show the plot, we use plt.show() method.
matplotlib bar chart tick labels
ax.set_xticklabels() and ax.set_yticklabels()

Read: Matplotlib rotate tick labels

Matplotlib bar chart label value

By using bar charts we can easily compare the data by observing the different heights of the bars. By default bar chart doesn’t display value labels on each of the bars.

To easy examine the exact value of the bar we have to add value labels on them. By using the plt.text() method we can easily add the value labels.

Matplotlib provides the functionalities to customize the value labels according to your choice.

The syntax to add value labels on a bar chart:

# To add value labels
matplotlib.pyplot.text(x, y, s, ha, vs, bbox)

The parameters used above are defined as below:

  • x: x – coordinates of the text.
  • y: y – coordinates of the text.
  • s: specifies the value label to display.
  • ha: horizontal alignment of the value label.
  • va: vertical alignment of the value label.
  • bbox: specifies rectangular shape box around the label value.

To understand the concept more clearly let’s see an example:

# Import library

import matplotlib.pyplot as plt
  
# Function to add value labels

def valuelabel(weight,students):
    for i in range(len(weight)):
        plt.text(i,students[i],students[i], ha = 'center',
                 bbox = dict(facecolor = 'cyan', alpha =0.8))
        
# Main function
  
if __name__ == '__main__':
    
    # Define data
    weight = ["35 Kg", "40 Kg", "43 Kg", "48 Kg", "65 Kg", "72    Kg"]
    students = [15, 12, 3, 5, 1, 2]
      
    # Plot bar chart
    plt.bar(weight, students, color= 'orange')
      
    # Call function
    valuelabel(weight, students)       
     
    # Define labels
    plt.xlabel("Weight of the students")
    plt.ylabel("Number of students")
      
    # Display plot
    plt.show()
  • Here we create a function valuelabel() which is used to add values on each of the bars. We use the for loop to calculate the length of the weight of students, so we pass len() method.
  • To customize the labels we set horizontal alignment parameter to center and also use bbox argument to define dictionary having a style of box.
  • plt.text() method is used to add the value labels, and we pass i and students[i] which represent the height and the string to be printed respectively.
  • In the main function, we define data points and after that, we plt.bar() method is used to plot the bar chart.
  • At last, we define labels on the axes, and plt.show() function is used to visualize the plot or chart.
matplotlib bar chart label value
plt.text() “Add label value”

Read: Matplotlib change background color

Matplotlib bar chart with string labels

Here we plot a bar chart having markers in the string data type. We plot the relation between the number of students who like different activities.

Let’s see an example of a bar chart with string labels:

# Import Library

import matplotlib.pyplot as plt

# Define Data

students = [5, 6, 2, 3]
activities= ["Joging", "Gyming", "Swimming", "Shopping"]

# Plot bar chart

plt.bar( activities, students, color= 'r')

# Display chart

plt.show()
  • In the above example, we simply define the data in string data type by phrasing it in quotation marks.
  • Here we define different activities by using double quotation marks so they can be represented in string format.
  • After this, we use plt.bar() method to plot a bar chart and we pass the color argument and set it to be red to change the color of the bars.
matplotlib bar chart with string labels
“String labels”

Read: Matplotlib scatter marker

Matplotlib bar chart labels vertical

By using the plt.bar() method we can plot the bar chart and by using the xticks(), yticks() method we can easily align the labels on the x-axis and y-axis respectively.

Here we set the rotation key to “vertical” so, we can align the bar chart labels in vertical directions.

Let’s see an example of vertical aligned labels:

# Import Library

import matplotlib.pyplot as plt

# Define Data

students = [5, 6, 2, 3]
subjects= ["English","Computers","Maths","Science"]

# Plot bar chart

plt.bar(subjects, students, color= 'm')

# Vertical aligned

plt.xticks(rotation='vertical')

                            #OR

plt.yticks(rotation='vertical')

# Display chart

plt.show()
  • In the above example, we import the matplotlib.pyplot library and after that, we define the data.
  • plt.bar() method is used to plot the bar chart between the number of students and subjects liked by them.
  • plt.xticks() method is used to align the xticks vertically.
  • plt.yticks() method is used for aligning the yticks vertically.
matplotlib bar chart labels vertical
plt.xticks(rotation=’vertical’)
matplotlib bar chart vertical labels
plt.yticks(rotation=’vertical’)

Read: Matplotlib dashed line

Matplotlib horizontal bar chart labels

In this section, we are going to learn how we create a horizontal bar chart, especially with data labels.

To plot a horizontal bar chart we use barh() method and we get the width of each bar to write data labels on bars of the bar chart.

The syntax to plot a horizontal bar chart:

matplotlib.pyplot.barh(x, height)
  • x: specifies x coordinates.
  • height: specifies y coordinates.

Let’s see an example of a horizontal bar chart with data labels:

# Import Library

import matplotlib.pyplot as plt

# Define Data

grades = ["A","B","C","D","E","Fail"]
students = [15, 12, 3, 5, 1, 2]

# Plot horizontal bar chart

bars = plt.barh(grades,students)

# To get data labels

for  bar in bars:
    width = bar.get_width()
    label_y = bar.get_y() + bar.get_height() / 2
    plt.text(width, label_y, s=f'{width}')
    
# Define axes labels

plt.xlabel("No. of students")
plt.ylabel("Grades of students")

# Display a bar chart
    
plt.show()
  • In the above example, firstly we import matplotlib.pyplot library and after that, we define the data.
  • We use plt.barh() method to plot horizontal bar chart.
  • Now, we need the width of each bar for that we get the position of y-axis labels by using the bar.get_y() method.
  • plt.text() method is used to add data labels on each of the bars and we use width for x position and to string to be displayed.
  • At last, we use the show() method to visualize the bar chart.
matplotlib horizontal bar chart labels
plt.barh()

Read: Matplotlib plot_date

Matplotlib bar chart x-axis label horizontal

By using the xticks() method we can easily align the labels on the x-axis. Here we have to set the rotation key to “horizontal” so, we can align the bar chart labels on the x-axis in horizontal directions.

Let’s see an example of horizontal aligned labels:

# Import Library

import matplotlib.pyplot as plt

# Define Data

students = [5, 6, 2, 3]
subjects= ["English","Computers","Maths","Science"]

# Plot bar chart

plt.bar(subjects, students, color= 'm')

# Horizontal aligned

plt.xticks(rotation='horizontal')
                           
# Display chart

plt.show()
  • In the above example, we import the matplotlib.pyplot library and after that, we define the data.
  • plt.bar() method is used to plot the bar chart between the number of students and subjects liked by them.
  • plt.xticks() method is used to align the xticks and we pass the rotation argument and set it value to horizontal.
matplotlib bar chart x-axis label horizontal
plt.xticks(rotation=’horizontal’)

Note: No change is observed in x-axis labels when we set rotation to horizontal, because by default x-axis labels are set to be horizontal.

Read Matplotlib save as pdf

Matplotlib bar chart label rotation

Matplotlib provides a feature to rotate axes labels of bar chart according to your choice. We can set labels to any angle which we like.

We have different methods to rotate bar chart labels:

  • By using plt.xticks()
  • By using ax.set_xticklabels()
  • By using ax.get_xticklabels()
  • By using ax.tick_params()

Matplotlib bar chart label rotation by plt.xticks()

Here we use plt.xticks() method to rotate x-axes labels and pass the rotation argument to it. We set the value of rotation to 30 degrees.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data

students = [5, 6, 2, 3]
activities= ["Joging", "Gyming", "Swimming", "Shopping"]

# Plot bar chart

plt.bar( activities, students, color= 'cyan')

# Rotation of x-axis label

plt.xticks(rotation=30)

# display chart

plt.show()
matplotlib bar chart label rotation
Rotation of x-axis labels to 30 degrees

Matplotlib bar chart label rotation by ax.set_xticklabels()

Here we use the ax.set_xticklabels() method to rotate x-axes labels and pass the rotation argument and labels that you want to rotate. We set the value of rotation to 15 degrees.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data

students = [5, 6, 2, 3]
activities= ["Joging", "Gyming", "Swimming", "Shopping"]

# Plot bar chart
ax = plt.subplot()

plt.bar( activities, students, color= 'cyan')

# Rotate labels

ax.set_xticklabels(activities, rotation=15)

# display chart

plt.show()
matplotlib bar chart label rotation
“Rotation of x-axis labels to 15 degrees”

Matplotlib bar chart label rotation by ax.get_xticklabels()

Here we use the ax.get_xticklabels() method to rotate x-axes labels.

Then we set the rotation of labels to 180 degrees.

The benefit of this method is we get a list of the labels and we loop through each label to set its rotation.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data

students = [5, 6, 2, 3]
activities= ["Joging", "Gyming", "Swimming", "Shopping"]

# Plot bar chart
ax = plt.subplot()

plt.bar( activities, students, color= 'cyan')

# Rotate labels

for label in ax.get_xticklabels(): 
    label.set_rotation(180)

# display chart

plt.show()
matplotlib label rotation bar chart
“Rotation of bar chart label at 180 degrees”

Matplotlib bar chart label rotation by ax.tick_params()

Here we use the ax.tick_params() method to rotate labels.

Then we pass the axis and labelrotation argument and set their value to x and 65 degrees respectively.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data


students = [5, 6, 2, 3]
activities= ["Joging", "Gyming", "Swimming", "Shopping"]

# Plot bar chart
ax = plt.subplot()

plt.bar( activities, students, color= 'cyan')

# Rotate labels

ax.tick_params(axis='x', labelrotation=65)

# Display chart

plt.show()
matplotlib rotate labels barcharts
“Labelroation at 65 degrees”

Read: Matplotlib log log plot

Matplotlib bar chart label font size

We can change the size of both data axes labels called tick labels and axes labels which tell what does axes represent to us.

You simply have to pass the argument fontsize and set their value.

Let’s see an example to change the font size of the labels:

# Import Library

import matplotlib.pyplot as plt

# Define Data

students = [5, 6, 2, 3]
subjects= ["English","Computers","Maths","Science"]

# Plot bar chart

plt.bar(subjects, students)

# Fontsize of tick labels


plt.xticks(fontsize=15,color='r')

# Font size of axes labels

plt.xlabel("Favourite subject", fontsize=15)
plt.ylabel("No.of.students", fontsize= 20)    

# Display chart

plt.show()
  • In the above example, by using the plt.bar() method we plot a bar chart.
  • plt.xticks() method is used to plot tick labels of bar chart and we pass an argument fontsize and color to it and set its value to 15 and red respectively.
  • plt.xlabel() method plot the x-axis label and we set the font size to 15.
  • plt.ylabel() method plots labels on the y-axis and we pass the fontsize parameter and set its value to 20.
matplotlib bar chart label font size
“Font size change”

Read: Matplotlib subplots_adjust

Matplotlib bar chart text labels

Here we learn how to add a text label in the specific bar of the bar chart. Firstly you have to define data and plot the bar by using the plt.bar() method.

After this use plt.text() method to add text label on the bar. Here we define the position or we can say coordinates of text label as ‘1′, ‘y[1]’ which means that we want to add text on the 2 bar of the bar chart.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data

x = ["A","B","C","D"]
y = [2, 6, 15, 10]

# Plot bar chart

plt.bar(x,y,color='pink')

# Add Text Label

plt.text(1,y[1],"Text Label",ha='center',fontsize=12)

# Plot bar chart

plt.show()
matplotlib bar chart text labels
“Text label at a specific position of the bar in bar chart”

Matplotlib grouped bar chart with labels

A bar chart is used to compare data in one or two dimensions. When we have to compare two dimensions data at that time we need a grouped bar chart.

Here we see an example of a grouped bar chart with labels:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data

labels = ['A', 'B', 'C', 'D', 'E', 'Fail']

Term1 = [30, 14, 20, 5, 7, 15]
Term2 = [45, 12, 24, 2, 6, 5]
x = np.arange(len(labels)) 

# Plot bar chart 

width = 0.4
fig, ax = plt.subplots()
rect1 = ax.bar(x - width/2, Term1, label='Term1')
rect2 = ax.bar(x + width/2, Term2, label='Term2')

# text in grouped bar chart

for bar in ax.patches:
    value = bar.get_height()
    text = f'{value}'
    text_x = bar.get_x() + bar.get_width() / 2
    text_y = bar.get_y() + value
    ax.text(text_x, text_y, text, ha='center',color='r',size=12)

# Add some text for labels,x-axis tick labels

ax.set_ylabel('No.of students')
ax.set_xlabel('Grades')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

# Display plot

plt.show()
  • Firstly, import the important libraries such as matplotlib.pyplot, and numpy. After this, we define data coordinates and labels, and by using arrange() method we find the label locations.
  • Set the width of the bars here we set it to 0.4. By using the ax.bar() method we plot the grouped bar chart.
  • Then we use for loop to add a text label in each bar of the bar chart.
  • get_height() method is used to get the height of the bars and to format the text we use f'{value}‘.
  • To get the middle of each bar on the x-axis we use get_x() and get_width() method. After this we add height to get_y() method because from get_y() bars starts.
  • Finally, we use the ax.text() method to add text on each bar of grouped bar chart and we set its color to red and change its size to 12.
  • plt.show() method is used to visualize the grounded bar chart.
matplotlib grouped bar chart with labels
“Grouped Bar Chart”

Read: Matplotlib best fit line

Matplotlib bar chart labels overlap

In this section, we will discuss a case when bar chart labels start overlapping each other. So we have to format them so the bar plot looks clean.

Let’s have a look at the below example:

# Import Library

import matplotlib.pyplot as plt

# Define Data 

x = ['I am the Label 1', "I am the Label 2", "I am the Label 3", "I am the Label 4"]

y = [2, 4, 5, 6]

# Plot Bar chart

ax= plt.subplot()
plt.bar(x, y)

# Display Chart

plt.show()
matplotlib bar chart labels overlap
“Overlapping Case In Bar Chart”

You have seen in this above output the x-axis labels of the bar chart overlap on each other and look so untidy.

Now, see the solution to overcome this problem:

In matplotlib, we have a function setp() which is used to set tick labels rotation and alignment properties.

The syntax of the setp() method is as below:

matplotlib.pyplot.setp(object, **kwargs)

The parameters used above is as described below:

  • object: specifies the artist object.
  • kwargs: specifies extra properties to change the style, rotation, etc.

Let’s understand this concept with the help of an example:

# Import Library

import matplotlib.pyplot as plt

# Define Data 

x = ['I am the Label 1', "I am the Label 2", "I am the Label 3", "I am the Label 4"]

y = [2, 4, 5, 6]

# Plot Bar chart

ax= plt.subplot()
plt.bar(x, y)

# Function to avoid overlapping

plt.setp(ax.get_xticklabels(), rotation=30, ha='right')

# Display Chart

plt.show()

In the above example, we use plt.setp() method and get.xticklabels() method to get ticklabels and we pass the rotation argument set its value to 30 degrees.

matplotlib bar chart overlap labels
“Bar Chart Labels without Overlapping”

Conclusion! plt.setp() method remove the overlapping problems and we get a clear view of the bar plot.

Read: Matplotlib subplot tutorial

Matplotlib bar chart diagonal tick labels

To set bar chart tick labels in the diagonal direction we have to set ticks rotation to 45 degrees and horizontal alignment to right.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data 

x = ['Label 1', "Label 2", "Label 3", "Label 4"]

y = [2, 4, 5, 6]

# Plot Bar chart

plt.bar(x, y)

# Diagonal tick labels

plt.xticks(rotation=45, ha="right")

# Display Chart

plt.show()
matplotlib bar chart diagonal tick labels
“Diagonal Tick Labels”

Read: Matplotlib plot bar chart

Matplotlib stacked bar chart with labels

A stacked bar chart shows comparisons between categories of data. Each segment of the bars represents different parts or categories.

Here we create a pandas data frame to create a stacked bar chart.

Let’s see an example of a stacked bar chart with labels:

# Import libraries

import matplotlib.pyplot as plt
import pandas as pd

# Define Data

df = pd.DataFrame({
    'Maths': [12, 15, 10, 3, 1, 5],
    'Science': [15, 10, 5, 4, 3, 6],
    'Computers':[20, 12, 5, 3, 5, 2]
})

labels = ['A','B','C','D','E','Fail']

# Plot stacked bar chart

ax = df.plot(stacked=True, kind='bar')

for bar in ax.patches:
    height = bar.get_height()
    width = bar.get_width()
    x = bar.get_x()
    y = bar.get_y()
    label_text = height
    label_x = x + width / 2
    label_y = y + height / 2
    ax.text(label_x, label_y, label_text, ha='center', va='center')
    
# Set Tick labels

ax.set_xticklabels(labels,rotation='horizontal')

# Display chart

plt.show()
  • In the above example, we import matplotlib.pyplot and pandas library.
  • After this, we create DataFrame and define labels.
  • Then by using plot() method plot stacked bar chart.
  • We define for loop in patches and patches consist everything inside the chart.
  • By using get_height() and get_width() method we get height and width.
  • At last, we use text() method to define height of each of the stacked bar.
matplotlib stacked bar chart with labels
“Stacked Bar Chart With Labels”

In this Python tutorial, we have discussed the “Matplotlib bar chart labels” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib bar chart labels
  • Matplotlib bar chart x-axis labels
  • Matplotlib bar chart y-axis labels
  • Matplotlib bar chart tick labels
  • Matplotlib bar chart label value
  • Matplotlib bar chart with string labels
  • Matplotlib bar chart labels vertical
  • Matplotlib horizontal bar chart labels
  • Matplotlib bar chart x-axis labels horizontal
  • Matplotlib bar chart label rotation
  • Matplotlib bar chart label font size
  • Matplotlib bar chart text labels
  • Matplotlib grouped bar chart with labels
  • Matplotlib bar chart labels overlap
  • Matplotlib bar chart diagonal tick labels
  • Matplotlib stacked bar chart with labels