Reputation: 477
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?
Upvotes: 11
Views: 25320
Reputation: 8387
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()
Upvotes: 3
Reputation: 5409
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])
Upvotes: 11
Reputation: 33409
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))
Upvotes: 4