Ploting of double Y-Axis

double y axis

Is it possible to plot this kind of graph for the comparison of two parameters having same reference?

Yes, It is possible to have two y-axes with a common x-axis as reference. by using twinx method which is available in matplotlib package.
The main intention behind plotting any two variables is to understand the variations and correlation between them.

Although we can directly plot the two variables in a single y-axis(having same scale range), It doesn’t make any sense to the end-user who is trying to find the insights from it. If the variables on the y-axis have different scale ranges then definitely we need to have a separate y-axis on the right side which helps in reducing the number of graphs.

In python, we can double the y-axis using twinx method available in matplotlib.


!pip install twinx
import pandas as pd
import matplotlib.pyplot as plt

Here we are using gapminder dataset and try to have a single y-axis.

	
# Carpentries link for gapminder data
data_url = 'http://bit.ly/2cLzoxH'
#load gapminder data from url as pandas dataframe
gapminder = pd.read_csv(data_url)
print(gapminder.head(3))
# selecting India country
gapminder_in = gapminder[gapminder.country=="India"]
# create figure and axis objects with subplots()
fig,ax=plt.subplots()
ax.plot(gapminder_in.year, gapminder_in.lifeExp, marker="o")
ax.set_xlabel("year")
ax.set_ylabel("lifeExp")
ax.plot(gapminder_in.year, gapminder_in["gdpPercap"], marker="o")
plt.show()

image

We can clearly see that the above graph does not make any sense and it is a bad idea to represent two variables in a single y-axis.

Using two different y-axis

# create figure and axis objects with subplots()
fig,ax = plt.subplots()
# make a plot
ax.plot(gapminder_in.year, gapminder_in.lifeExp, color="red", marker="o")
# set x-axis label
ax.set_xlabel("year",fontsize=14)
# set y-axis label
ax.set_ylabel("lifeExp",color="red",fontsize=14)
# twin object for two different y-axis on the sample plot
ax2=ax.twinx()
# make a plot with different y-axis using second axis object
ax2.plot(gapminder_in.year, gapminder_in["gdpPercap"],color="blue",marker="o")
ax2.set_ylabel("gdpPercap",color="blue",fontsize=14)
plt.show()
# save the plot as a file
fig.savefig('two_different_y_axis_for_single_python_plot_with_twinx.jpg',
            format='jpeg',
            dpi=100,
            bbox_inches='tight')

From the above figure , we can clearly see the change of lifeExp (left) with respective to change in a year. Also, we can clearly notice the change of gdpPercap (right) with respect to the change in a year.

references:

https://matplotlib.org/stable/gallery/subplots_axes_and_figures/secondary_axis.html

https://cmdlinetips.com/2019/10/how-to-make-a-plot-with-two-different-y-axis-in-python-with-matplotlib/

1 Like