The Wayback Machine - https://web.archive.org/web/20240719160749/https://www.geeksforgeeks.org/how-to-add-a-y-axis-label-to-the-secondary-y-axis-in-matplotlib/
Open In App

How to Add a Y-Axis Label to the Secondary Y-Axis in Matplotlib?

Last Updated : 04 Aug, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Sometimes while analyzing any data through graphs we need two x or y-axis to get some more insights into the data. Matplotlib library of Python is the most popular data visualization library, and we can generate any type of plot in Matplotlib. We can create a plot that has two y-axes and can provide different labels to both of the y-axis. We can make a plot with two different y-axes by creating or using two different axes objects with the help of twinx() function. First, we create figure and axis objects and make the first plot. And we also set the x and y-axis labels with the help of the axis object created.

Axes object: Axes are the most basic and flexible unit for creating subplots. Axes are used for the placement of plots at any location in the figure. A given figure of the plot can contain many axes, but a given axes object can only be in one figure of the plot. 

Approach:

  • Import packages.
  • Use the axes object and create a subplot.
  • Using the twinx() define the plot values.
  • Now label the axis.
  • Show plot.

Example 1:

In this example we have created a plot with two different y-axes by using two different axes objects a and a2 with the help of twinx() function. ax.twinx() creates a new Axes object ax2 for a y-axis that is opposite to the original y-axis. The second axes object ax2 is used to make the plot of the second y-axis variable and to update its label.

Python3




# Adding a Y-Axis Label to the Secondary Y-Axis in Matplotlib
# importing the libraries
import numpy as np
import matplotlib.pyplot as plt
 
# creating data for plot
# data arrangement between 0 and 50
# with the difference of 2
# x-axis
x = np.arange(0, 50, 2)
 
# y-axis values
y1 = x**2
 
# secondary y-axis values
y2 = x**3
 
# plotting figures by creating axes object
# using subplots() function
fig, ax = plt.subplots(figsize = (10, 5))
plt.title('Example of Two Y labels')
 
# using the twinx() for creating another
# axes object for secondary y-Axis
ax2 = ax.twinx()
ax.plot(x, y1, color = 'g')
ax2.plot(x, y2, color = 'b')
 
# giving labels to the axises
ax.set_xlabel('x-axis', color = 'r')
ax.set_ylabel('y1-axis', color = 'g')
 
# secondary y-axis label
ax2.set_ylabel('Secondary y-axis', color = 'b')
 
# defining display layout
plt.tight_layout()
 
# show plot
plt.show()


Output:

 

Example 2: 

In this example we have created a bar plot using same method. 

Python3




# Adding a Y-Axis Label to the
# Secondary Y-Axis in Matplotlib
# importing the libraries
import numpy as np
import matplotlib.pyplot as plt
 
# creating data for plot
# data arrangement between 0 and 50 with the difference of 2
# x-axis values
x = np.arange(0, 50, 2)
 
#y-axis values
y1 = x**2
 
# secondary y-axis values
y2 = x**3
 
# plotting figures by creating axes object
# using subplots() function
fig, ax = plt.subplots(figsize = (10, 5))
plt.title('Example of Two Y labels')
 
# using the twinx() for creating
# another axes object for secondary y-Axis
ax2 = ax.twinx()
# creating a bar plot
ax.bar(x, y1, color = 'g')
ax2.bar(x, y2, color = 'b')
 
# giving labels to the axises
ax.set_xlabel('x-axis', color = 'r')
ax.set_ylabel('y1-axis', color = 'g')
 
# secondary y-axis label
ax2.set_ylabel('Secondary y-axis', color = 'b')
 
# defining display layout
plt.tight_layout()
 
# show plot
plt.show()


Output:

Example 3: 

We can add a y-axis label to the secondary y-axis in pandas too. Generating a plot from DataFrame and also without using twinx() function. In this example, we will use simple DataFrame.plot() function with some parameters to specify the plot.

When we set the secondary_y parameter to be True in DataFrame.plot method, it returns different axes that can be used to set the labels.

Python3




# Adding a Y-Axis Label to
# the Secondary Y-Axis in Matplotlib
# importing the libraries
import pandas as pd
import matplotlib.pyplot as plt
 
#creating dataframe for plot
dataset = pd.DataFrame({'Name':['Rohit', 'Seema',
                                'Meena', 'Geeta',
                                'Rajat'],
                         
                   'Height': [155,129,138,164,145],
                   'Weight': [60,40,45,55,60]})
 
# creating axes object and defining plot
ax = dataset.plot(kind = 'line', x = 'Name',
                  y = 'Height', color = 'Blue',
                  linewidth = 3)
 
ax2 = dataset.plot(kind = 'line', x = 'Name',
                   y = 'Weight', secondary_y = True,
                   color = 'Red',  linewidth = 3,
                   ax = ax)
 
#title of the plot
plt.title("Student Data")
 
#labeling x and y-axis
ax.set_xlabel('Name', color = 'g')
ax.set_ylabel('Height', color = "b")
ax2.set_ylabel('Weight', color = 'r')
 
#defining display layout
plt.tight_layout()
 
#show plot
plt.show()


Output:

In above example, the plot is created without using twinx() function, but we have created two axis object ax and ax2 as given in other examples for two y-axis to make the plot with two y-axis and update its label.



Similar Reads

Change the label size and tick label size of colorbar using Matplotlib in Python
In this article, we will learn how to change the label size and tick label size of colorbar in Matplotlib using Python. Labels are a kind of assigning name that can be applied to any node in the graph. They are a name only and so labels are either present or absent. To properly label a graph, helps to identify the x-axis and y-axis. Each tick mark
2 min read
How to Rotate X-Axis Tick Label Text in Matplotlib?
Matplotlib is an amazing and one of the most widely used data visualization libraries in Python for plots of arrays. It is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It is much popular because of its customization options as we can tweak about any element from its hierarchy o
3 min read
How to plot on secondary Y-Axis with Plotly Express in Python?
Perquisites: Python Plotly In this article, we will learn how to plot on secondary y-Axis with plotly express. One of the most deceptively-powerful features of Plotly data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears. It provides us t
3 min read
Matplotlib.axis.Axis.get_minorticklines() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. matplotlib.axis.Axis.get_minorticklines() Function The Axis.get_minorticklines() function in axis module of matplotlib library is
2 min read
Matplotlib.axis.Axis.set_figure() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.set_figure() Function The Axis.set_figure() function in axis module of matplotlib library is used to set the
2 min read
Matplotlib.axis.Axis.remove_overlapping_locs() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.remove_overlapping_locs Function The Axis.remove_overlapping_locs function in axis module of matplotlib libr
2 min read
Matplotlib.axis.Axis.set_tick_params() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.set_tick_params() Function The Axis.set_tick_params() function in axis module of matplotlib library is used
2 min read
Matplotlib.axis.Axis.get_figure() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.get_figure() Function The Axis.get_figure() function in axis module of matplotlib library is used to get the
2 min read
Matplotlib.axis.Axis.cla() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. matplotlib.axis.Axis.cla() Function The Axis.cla() function in axis module of matplotlib library is used to clear this axis. Synt
2 min read
Matplotlib.axis.Axis.get_major_locator() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. matplotlib.axis.Axis.get_major_locator() Function The Axis.get_major_locator() function in axis module of matplotlib library is u
1 min read
three90RightbarBannerImg