Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyplot - rescaling y axis after limiting x axis

I'm trying to plot some data using pyplot, and then 'zoom in' by using xlim() the x axis. However, the new plot doesn't rescale the y axis when I do this - am I doing something wrong?

Example - in this code, the plot y-axis range still takes a maximum of 20, rather than 10.:

from pylab import *

x = range(20)
y = range(20)

xlim(0,10)
autoscale(enable=True, axis='y', tight=None)
scatter(x,y)
show()
close()
like image 636
etsu Avatar asked Oct 18 '11 03:10

etsu


1 Answers

Realize this is an ancient question, but this is how I've (messily) gotten around the issue:

  1. use .plot() instead of .scatter()
  2. access plot data later (even after a figure is returned somewhere) with ax.get_lines()[0].get_xydata()
  3. use that data to rescale y axis to xlims

Snippet should work:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

x = range(20)
y = range(20)

xlims = [0, 10]

ax.set_xlim(xlims)
ax.plot(x, y, marker='.', ls='')

# pull plot data
data = ax.get_lines()[0].get_xydata()

# cut out data in xlims window
data = data[np.logical_and(data[:, 0] >= xlims[0], data[:, 0] <= xlims[1])]

# rescale y
ax.set_ylim(np.min(data[:, 1]), np.max(data[:, 1]))

plt.show()
like image 54
zgazak Avatar answered Sep 30 '22 22:09

zgazak