Pyplot - 限制x轴后重新缩放y轴
我正在使用pyplot来绘制一些数据,然后想通过使用xlim()来“放大”x轴的范围。但是,当我这样做时,新的图表并没有重新调整y轴的范围——我是不是做错了什么?
举个例子——在这段代码中,图表的y轴范围仍然是最大20,而不是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()
2 个回答
-1
我不知道,不过你可以试着手动筛选这些点,使用下面的代码:
scatter([(a,b) for a,b in zip(x,y) if a>0 and a<10])
1
我知道这个问题已经很久了,但这是我(有点乱)解决这个问题的方法:
- 用
.plot()
代替.scatter()
- 之后可以通过
ax.get_lines()[0].get_xydata()
来获取图表的数据(即使图形已经返回到其他地方) - 用这些数据来调整 y 轴的范围,使其适应 x 轴的范围
下面的代码片段应该可以正常工作:
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()