Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I align gridlines for two y-axis scales using Matplotlib?

I'm plotting two datasets with different units on the y-axis. Is there a way to make the ticks and gridlines aligned on both y-axes?

The first image shows what I get, and the second image shows what I would like to get.

This is the code I'm using to plot:

import seaborn as sns import numpy as np import pandas as pd  np.random.seed(0) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(pd.Series(np.random.uniform(0, 1, size=10))) ax2 = ax1.twinx() ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r') 

Example of unwanted behavior

Example of wanted behavior

like image 732
Artturi Björk Avatar asked Nov 05 '14 08:11

Artturi Björk


People also ask

How do I plot multiple Y-axis in Matplotlib?

Using subplots() method, create a figure and a set of subplots. Plot [1, 2, 3, 4, 5] data points on the left Y-axis scales. Using twinx() method, create a twin of Axes with a shared X-axis but independent Y-axis, ax2. Plot [11, 12, 31, 41, 15] data points on the right Y-axis scale, with blue color.

How do you plot a double Y-axis in Python?

The way to make a plot with two different y-axis is to use two different axes objects with the help of twinx() function. We first create figure and axis objects and make a first plot. In this example, we plot year vs lifeExp. And we also set the x and y-axis labels by updating the axis object.


2 Answers

I am not sure if this is the prettiest way to do it, but it does fix it with one line:

import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd  np.random.seed(0) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(pd.Series(np.random.uniform(0, 1, size=10))) ax2 = ax1.twinx() ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r')  # ADD THIS LINE ax2.set_yticks(np.linspace(ax2.get_yticks()[0], ax2.get_yticks()[-1], len(ax1.get_yticks())))  plt.show() 
like image 112
Leo Avatar answered Sep 22 '22 13:09

Leo


I could solve it by deactivating ax.grid(None) in one of the grid`s axes:

import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd  fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(pd.Series(np.random.uniform(0, 1, size=10))) ax2 = ax1.twinx() ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r') ax2.grid(None)  plt.show() 

Figure Result

like image 34
arnaldo Avatar answered Sep 19 '22 13:09

arnaldo