How to Add a Y-Axis Label to the Secondary Y-Axis in Matplotlib?
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.
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.
In this example we have created a bar plot using same method.
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.
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.