Matplotlib two y axes

In this Python tutorial, we will discuss Matplotlib two y axes in python. Here we will cover different examples related to two y axes using matplotlib. And we will also cover the following topics:

  • Matplotlib two y axes
  • Matplotlib two y axes same data
  • Matplotlib two y axes legend
  • Matplotlib two y axes different scale
  • Matplotlib two y axes same scale
  • Matplotlib two y axes bar plot
  • Matplotlib two y axis grid

Matplotlib two y axes

In this section, we learn about how to plot a graph with two y-axes in matplotlib in Python. When we need a quick analysis, at that time we create a single graph with two data variables with different scales.

In matplotlib, the twinx() function is used to create dual axes.

The syntax of the twinx() method is as given below:

matplotlib.axes.Axes.twinx(self)

Let’s see an example where we create two y-axes:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 
  
# Define Data

x = np.arange(0, 15, 0.2)
data_1 = np.sin(x)
data_2 = np.cos(x) 
  
# Create Plot

fig, ax1 = plt.subplots() 
  
ax1.set_xlabel('X-axis') 
ax1.set_ylabel('Y1-axis', color = 'red') 
ax1.plot(x, dataset_1, color = 'red') 
ax1.tick_params(axis ='y', labelcolor = 'red') 
  
# Adding Twin Axes

ax2 = ax1.twinx() 
  
ax2.set_ylabel('Y2-axis', color = 'blue') 
ax2.plot(x, dataset_2, color = 'blue') 
ax2.tick_params(axis ='y', labelcolor = 'blue') 
 
# Show plot

plt.show()
  • In the above example, we firstly import numpy and matplotlib.pyplot library.
  • Next we define data using arrange(), sin(), and cos() method.
  • Then we plot data between x-axis and y1-axis by using plot() method.
  • After this, we plot data between x-axis and y2-axis by using plot() method.
  • twinx() method is used to create two y-axis.
matplotlib two y axes
twinx()

Matplotlib two y axes same data

Here we are going to learn how to create two y-axes with the same data plotting in Python Matplotlib.

By using the twinx() method we create two twin y-axes.

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(100)
y = np.sin(x)

# Plot Graph

fig, ax1 = plt.subplots()
ax1.plot(x, y)

# Define Labels

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y1-axis')

# Twin Axes

ax2 = ax1.twinx()
ax2.set_ylabel('Y2-axis')

# Display

plt.show()

In the above example, by using the twinx() method we create two y-axes and plot the same data by using the plot() method.

matplolib two y axes same data
” Two y-axes with same data “

Matplotlib two y axes legend

In matplotlib, by using the plt.legend() method we can add legends to the plot.

The syntax is as follow:

matplotlib.pyplot.legend()

Let’s see an example to better understand the concept:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 
  
# Define Data

x = np.arange(0, 15, 0.2)
data_1 = np.sin(x)
data_2 = np.cos(x) 
  
# Create Plot

fig, ax1 = plt.subplots() 
  
ax1.set_xlabel('X-axis') 
ax1.set_ylabel('Y1-axis', color = 'red') 
plot_1 = ax1.plot(x, data_1, color = 'red', label='Sin x') 
ax1.tick_params(axis ='y', labelcolor = 'red') 

# Adding Twin Axes

ax2 = ax1.twinx() 
  
ax2.set_ylabel('Y2-axis', color = 'blue') 
plot_2 = ax2.plot(x, data_2, color = 'blue', label = 'Cos x') 
ax2.tick_params(axis ='y', labelcolor = 'blue') 

# Add legends

lns = plot_1 + plot_2
labels = [l.get_label() for l in lns]
plt.legend(lns, labels, loc=0)
 
# Show plot

plt.show()
  • In the above example, we firstly import numpy and matplotlib.pyplot library.
  • Next we define, data using arrange(), sin(), and cos() method.
  • Then we plot data by using plot() method and pass label as an argument to define legends.
  • After this, we use twinx() method is used to create two y-axis.
  • plt.legend() method is used to add legend to the plot.
matplotlib two y axes legend
plt.legend()

Matplotlib two y axes different scale

Here we are going to learn how to plot two y-axes with different scales in Matplotlib. It simply means that two plots on the same axes with different y-axes or left and right scales.

By using the Axes.twinx() method we can generate two different scales.

Let’s see an example of two y-axes with different left and right scales:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 
  
# Define Data

x = np.arange(0, 15, 0.2)
data_1 = np.tan(x)
data_2 = np.exp(x) 
  
# Create Plot

fig, ax1 = plt.subplots() 
  
ax1.set_xlabel('X-axis') 
ax1.set_ylabel('Y1-axis', color = 'black') 
plot_1 = ax1.plot(x, data_1, color = 'black') 
ax1.tick_params(axis ='y', labelcolor = 'black') 

# Adding Twin Axes

ax2 = ax1.twinx() 
  
ax2.set_ylabel('Y2-axis', color = 'green') 
plot_2 = ax2.plot(x, data_2, color = 'green') 
ax2.tick_params(axis ='y', labelcolor = 'green') 

# Show plot

plt.show()
  • In the above example, we import matplotlib.pypot and numpy as a library.
  • After this we define data by using arrange(), tan(), and exp() method of numpy.
  • Then by using the ax1.plot() method we plot a graph of the tan function.
  • To add twin axes we use the twinx() method.
  • Next, we use ax2.plot() method to plot a graph of exponent function.
matplotlib two y axes different scale
” Two y-axes with different scales “

Here you observed that the range of the Y1-axis is (-200 – 0) and the range of the Y2-axis is (0 – 2.5). Hence, both axes have different scales.

Matplotlib two y axes same scale

As we study above to create two y-axes we use the twinx() method, but it creates axes with different scales.

Now, what do we have to do if we want to create two y-axes with the same scale? For this, we have to set the view limits of the y-axis.

The syntax to set view limits of y-axis:

matplotli.axes.Axes.set_ylim(bottom=None, top=None, emit= True, auto=False, ymin=None, ymax=None)

The parameters used above are outlined below:

  • bottom: specify bottom ylim in data coordinates.
  • top: specify top ylim in data coordinates.
  • emit: used to notify observers of limit change.
  • auto: used to turn on auto calling.
  • ymin, ymax: It is an error to pass both ymin and bottom or ymax and top.

Let’s see an example where we have the same scale on the y-axis:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 
  
# Define Data

x = np.arange(0, 15, 0.2)
data_1 = np.tan(x)
data_2 = np.exp(x) 
  
# Create Plot

fig, ax1 = plt.subplots() 
  
ax1.set_xlabel('X-axis') 
ax1.set_ylabel('Y1-axis', color = 'black') 
plot_1 = ax1.plot(x, data_1, color = 'black') 
ax1.tick_params(axis ='y', labelcolor = 'black') 

# Adding Twin Axes

ax2 = ax1.twinx() 
  
ax2.set_ylabel('Y2-axis', color = 'green') 
plot_2 = ax2.plot(x, data_2, color = 'green') 
ax2.tick_params(axis ='y', labelcolor = 'green') 

# Set same axes sacles

a,b = -200, 200
ax1.set_ylim(a,b)
ax2.set_ylim(a,b)

# Show plot

plt.show()
  • In the above example, we import matplotlib.pypot and numpy as a library.
  • After this we define data by using arange(), tan(), and exp() method of numpy.
  • By using the ax1.plot() and ax.2plot() method we plot a graph.
  • To add twin axes we use the twinx() method.
  • Now, to make both the sclaes of the y-axes same use set_ylim() method.
  • Here we set the view limits of both the y-axis from -200 to 200.
matplotlib two y axes same scale
” Tow y-axes with the same scale “

Matplotlib two y axes bar plot

Here we are going to create a bar plot with two y-axes in Python matplotlib. Firstly you have to know how to create a bar plot.

The syntax to create a bar plot is as given below:

matplotlib.pyplot.bar(x, height)

Let’s see an example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

x = np.arange(15, 50, 1.5)
y1 = x**4
y2 = x**5
 
# using subplots() function

fig, ax = plt.subplots(figsize = (10, 5))
 
# using the twinx() for creating
# another axes

ax2 = ax.twinx()

# creating a bar plot

ax.bar(x, y1, color = 'yellow')
ax2.bar(x, y2, color = 'cyan')
 
# Label axes

ax.set_xlabel('X-axis')
ax.set_ylabel('Y1-axis')
ax2.set_ylabel('Y2-axis')
 
# defining layout

plt.tight_layout()
 
# show plot

plt.show()
  • In the above example, we firstly import matplotlib.pyplot and numpy library for data visualization.
  • After this, we define data using arange() method.
  • By using the subplots() function we create a subplot.
  • Then we create two different y-axes by using two different axes object with the help of the twinx() method is used to create dual y-axes.
  • Then we create bar chart by using ax.bar() method and ax2.bar() method. Here ax is an object of the simple Y-axis and ax2 is an object of the secondary Y-axis.
  • By using set_ylabels() and set_xlabels() method we set labels of the plot.
  • In last, we use plt.tight_layou() method and plt.show() method for defining the layout and to show the plot respectively.
matplotlib two y axes bar plot
plt.bar()

Matplotlib two y axis grid

Here we are going to learn how to create a grid from any of the axes of the plot out of two y-axes in matplotlib.

For this, we have to use the grid() method with the axes object of the plot to which we want to create grid lines.

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(100)
y = np.sin(x)

# Plot Graph

fig, ax1 = plt.subplots(figsize=(10,5.5))
ax1.plot(x, y)

# Define Labels

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y1-axis')

# Twin Axes

ax2 = ax1.twinx()
ax2.set_ylabel('Y2-axis')

# Grid method

ax1.grid()

# Display

plt.show()
  • In the above example, we import matplotlib.pyplot and numpy library.
  • Then we define data using the arange() and sin() method.
  • By using the plot() method we plot a graph.
  • Next, we use the twinx() method to create another y-axis.
  • Now by using the grid() method with the ax1 object of the axes we create a grid line along with Y1-axis scales.
matplotlib two y axis grid
” Grid lines along Y1-axis scales “

You may also like the following Python Matplotlib tutorials:

In this Python tutorial, we have discussed the “Matplotlib two y axes” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib two y axes
  • Matplotlib two y axes same data
  • Matplotlib two y axes legend
  • Matplotlib two y axes different scale
  • Matplotlib two y axes same scale
  • Matplotlib two y axes bar plot
  • Matplotlib two y axis grid