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

30 Aug, 2021
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. 
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 librariesimport numpy as npimport matplotlib.pyplot as plt # creating data for plot# data arrangement between 0 and 50# with the difference of 2# x-axisx = np.arange(0, 50, 2) # y-axis valuesy1 = x**2 # secondary y-axis valuesy2 = x**3 # plotting figures by creating aexs object# using subplots() functionfig, ax = plt.subplots(figsize = (10, 5))plt.title('Example of Two Y labels') # using the twinx() for creating another# axes object for secondary y-Axisax2 = ax.twinx()ax.plot(x, y1, color = 'g')ax2.plot(x, y2, color = 'b') # giving labels to the axisesax.set_xlabel('x-axis', color = 'r')ax.set_ylabel('y1-axis', color = 'g') # secondary y-axis labelax2.set_ylabel('Secondary y-axis', color = 'b') # defining display layoutplt.tight_layout() # show plotplt.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 librariesimport numpy as npimport matplotlib.pyplot as plt # creating data for plot# data arrangement between 0 and 50 with the difference of 2# x-axis valuesx = np.arange(0, 50, 2) #y-axis valuesy1 = x**2 # secondary y-axis valuesy2 = x**3 # plotting figures by creating aexs object# using subplots() functionfig, ax = plt.subplots(figsize = (10, 5))plt.title('Example of Two Y labels') # using the twinx() for creating# another axes object for secondary y-Axisax2 = ax.twinx()# creating a bar plotax.bar(x, y1, color = 'g')ax2.bar(x, y2, color = 'b') # giving labels to the axisesax.set_xlabel('x-axis', color = 'r')ax.set_ylabel('y1-axis', color = 'g') # secondary y-axis labelax2.set_ylabel('Secondary y-axis', color = 'b') # defining display layoutplt.tight_layout() # show plotplt.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 librariesimport pandas as pdimport matplotlib.pyplot as plt #creating dataframe for plotdataset = 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 plotax = 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 plotplt.title("Student Data") #labeling x and y-axisax.set_xlabel('Name', color = 'g')ax.set_ylabel('Height', color = "b")ax2.set_ylabel('Weight', color = 'r') #defining display layoutplt.tight_layout() #show plotplt.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.
ruhelaa48
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list