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 = ''
#load gapminder data from url as pandas dataframe
gapminder = pd.read_csv(data_url)
# selecting India country
gapminder_in = gapminder["India"]
# create figure and axis objects with subplots()
ax.plot(gapminder_in.year, gapminder_in.lifeExp, marker="o")
ax.plot(gapminder_in.year, gapminder_in["gdpPercap"], marker="o")


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
# set y-axis label
# twin object for two different y-axis on the sample plot
# make a plot with different y-axis using second axis object
ax2.plot(gapminder_in.year, gapminder_in["gdpPercap"],color="blue",marker="o")
# save the plot as a file

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.


1 Like