11

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?

2

3 Answers 3

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])
Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.