1123581321
1123581321

Reputation: 209

Easy way to change axis limits in subplots

How do I change the limits on the axes in matplotlib subplots?

For example if I have

x = np.linspace(0,4*np.pi,100)

plt.figure(1)
plt.subplot(121)
plt.plot(x,np.sin(x))
plt.xlim([0,4*np.pi])
plt.ylim([-1,1])
plt.axis('equal')

plt.subplot(122)
plt.plot(x,np.cos(x))
plt.xlim([0,4*np.pi])
plt.ylim([-1,1])
plt.axis('equal')

I tried using plt.xlim and plt.ylim but these didn't work.

Upvotes: 1

Views: 4548

Answers (1)

Hami
Hami

Reputation: 714

What you have works if you just remove the plt.axis('equal') lines.

EDIT: To answer your comment considering scales, this is the code that should work:

import numpy as np
import matplotlib.pyplot as plt   

x = np.linspace(0,4*np.pi,100)

plt.figure(1)
plt.subplot(121)
plt.plot(x,np.sin(x))
plt.xlim([0,4*np.pi])
plt.ylim([-1,1])
plt.gca().set_aspect('equal', adjustable='box')


plt.subplot(122)
plt.plot(x,np.cos(x))
plt.xlim([0,4*np.pi])
plt.ylim([-2*np.pi,2*np.pi])
plt.gca().set_aspect('equal', adjustable='box')

Output image showing proper scales

Solution courtesy of How to equalize the scales of x-axis and y-axis in Python matplotlib?

Upvotes: 1

Related Questions