Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set same scale for subplots in python using matplotlib

I want to compare subplots visually with ease. To do this, I want to set the same scale for all subplots.

My code works fine, and I'm able to plot subplots, but with their own scales. I want to maintain the scale on the x axis.

like image 488
maulik mehta Avatar asked Oct 06 '15 17:10

maulik mehta


People also ask

How do you make all subplots the same size in Python?

To change the size of subplots in Matplotlib, use the plt. subplots() method with the figsize parameter (e.g., figsize=(8,6) ) to specify one size for all subplots — unit in inches — and the gridspec_kw parameter (e.g., gridspec_kw={'width_ratios': [2, 1]} ) to specify individual sizes.

How do I make axis scales the same in Matplotlib?

If we use "equal" as an aspect ratio in the function, we get a plot with the same scaling from data points to plot units for X-axis and Y-axis. It sets both X-axis and Y-axis to have the same range. Then ax. set_aspect('equal') sets both axes to be equal.


2 Answers

If you want to have two subplots with the same xaxis, you can use the sharex-keyword when you create the second axes:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)


t = np.linspace(0, 1, 1000)

ax1.plot(t, np.sin(2 * np.pi * t))
ax2.plot(t, np.cos(2 * np.pi * t))

plt.show()

Result: result

like image 190
MaxNoe Avatar answered Oct 23 '22 12:10

MaxNoe


If you want to use subplots:

fig,axs = plt.subplots(2,1, figsize = (10,8), sharex=True)

x = np.random.randn(1000)
x1 = x + 3
sns.histplot(x, ax = axs[0])
sns.histplot(x1, ax = axs[1])
fig.show()

enter image description here

like image 45
sushmit Avatar answered Oct 23 '22 10:10

sushmit