nivniv
nivniv

Reputation: 3722

How to change the size of plot with equal aspect ratio?

It seems that I can't have both setting equal axes scales AND setting the size of the plot. What I'm doing is:

fig = pl.figure(figsize=(20,20))
ax = fig.add_subplot(111)
ax.set_aspect('equal')

If I remove the figsize the plot seems to have equal scales, but with figsize I have a bigger plot but the scales aren't equal anymore.

Edit: The graph does not necessarily have to be square, just bigger.. please assume that I don't now the exact ratio of the axes

Any solutions?

Thanks

Upvotes: 1

Views: 2185

Answers (1)

xnx
xnx

Reputation: 25478

If you want to change the data limits to make the axes square, add datalim to your call to set_aspect:

ax.set_aspect('equal', 'datalim')

If you want the scaling to change so that the limits are different but the axes look square, you can calculate the axis size ratio and set it explicitly:

ax.set_aspect(1./ax.get_data_ratio())

e.g.

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(7,7))
ax = fig.add_subplot(111)

x = np.linspace(0,np.pi,1000)
y = np.sin(3*x)**2
ax.plot(x,y)
ax.set_aspect('equal', 'datalim')
plt.show()

enter image description here

or

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(7,7))
ax = fig.add_subplot(111)

x = np.linspace(0,np.pi,1000)
y = np.sin(3*x)**2
ax.plot(x,y)
ax.set_aspect(1./ax.get_data_ratio())
plt.show()

enter image description here

Upvotes: 1

Related Questions