10

I am using matplotlib.pyplot in python to plot my data. The problem is the image it generates seems to be autoscaled. How can I turn this off so that when I plot something at (0,0) it will be placed fixed in the center?

Scimonster
  • 32,893
  • 9
  • 77
  • 89
overmind
  • 467
  • 1
  • 8
  • 17

3 Answers3

11

You want the autoscale function:

from matplotlib import pyplot as plt

# Set the limits of the plot
plt.xlim(-1, 1)
plt.ylim(-1, 1)

# Don't mess with the limits!
plt.autoscale(False)

# Plot anything you want
plt.plot([0, 1])
Marijn van Vliet
  • 5,239
  • 2
  • 33
  • 45
4

You can use xlim() and ylim() to set the limits. If you know your data goes from, say -10 to 20 on X and -50 to 30 on Y, you can do:

plt.xlim((-20, 20))
plt.ylim((-50, 50))

to make 0,0 centered.

If your data is dynamic, you could try allowing the autoscale at first, but then set the limits to be inclusive:

xlim = plt.xlim()
max_xlim = max(map(abs, xlim))
plt.xlim((-max_xlim, max_xlim))
ylim = plt.ylim()
max_ylim = max(map(abs, ylim))
plt.ylim((-max_ylim, max_ylim))
Scimonster
  • 32,893
  • 9
  • 77
  • 89
3

If you want to keep temporarily turn off the auto-scaling to make sure that the scale stays as it was at some point before drawing the last piece of the figure, this might become handy and seems to work better then plt.autoscale(False) as it actually preserves limits as they would have been without the last scatter:

from contextlib import contextmanager

@contextmanager
def autoscale_turned_off(ax=None):
  ax = ax or plt.gca()
  lims = [ax.get_xlim(), ax.get_ylim()]
  yield
  ax.set_xlim(*lims[0])
  ax.set_ylim(*lims[1])

plt.scatter([0, 1], [0, 1])
with autoscale_turned_off():
  plt.scatter([-1, 2], [-1, 2])
plt.show()

plt.scatter([0, 1], [0, 1])
plt.scatter([-1, 2], [-1, 2])
plt.show()

enter image description here enter image description here

Ben Usman
  • 7,969
  • 6
  • 46
  • 66