How to set same scale for subplots

Question:

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.

Asked By: maulik mehta

||

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

Answered By: 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

Answered By: sushmit
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.