作为演示,我绘制了 x^0 到 x^9,其中 x 值的范围为 10 到 20。
然后我对这些图像进行切片,得到 9 个切片:
x = (10 到 11), (11 到 12) 等等到 (18 到 19)
我希望裁剪图像,以便 y 值始终在每个切片中从上到下分布,但我得到的是自动缩放始终缩放到完整数据集而不是当前切片。
import matplotlib.pyplot as plt
import numpy as np
# create some test data
for i in range(10):
x = np.arange(10,20)
y = x**i
plt.plot(x,y,c='red',marker='.',ms=2)
# get all x values in chart and reduce to a sorted list set
xd = []
for n in range(len(plt.gca().get_lines())):
line = plt.gca().get_lines()[n]
xd.append((line.get_xdata()).tolist())
xd = [item for sublist in xd for item in sublist]
xd = sorted(list(set(xd)))
# attempt to plot slices of x with autoscaled y
ax = plt.gca()
for i in range(len(xd)-1):
ax.set_xlim([xd[i],xd[i+1]])
ax.axes.autoscale(enable=True,axis='y', tight=True)
plt.pause(1) #timing
#uncommenting the next line will create nine tiny (6kb) image files
#plt.savefig(('image_%s.png' % i), bbox_inches=0, dpi=48)
在我的实际应用程序中,我尝试以这种方式从随机数据生成 100k 个微小图像作为数据库。对于每个 x,都有 2 到 200 个 y 值。然后,我使用 OpenCV 对新图像进行图像匹配,以使其与历史数据库最匹配。
至关重要的是,OpenCV 在每个图像中从上到下拉伸 y 值以找到良好的匹配。
如果它有帮助,我的 x 值将始终是 int() 类型且等距
ETA:我尝试在这里实施一些解决方案,但没有取得任何进展:
Matplotlib - 修复 x 轴刻度和自动缩放 y 轴
Matplotlib基于手动缩放的x轴缩放y轴
但至少我学到了:
自动缩放始终使用整个数据范围,因此 y 轴是
按 y 数据的全部范围进行缩放,而不仅仅是按 y 数据范围内的内容进行缩放
x 限制。
但仍然没有在这里有效的解决方案
def autoscale_y()
由@DanHickstein 提出
给我:
h = np.max(y_displayed) - np.min(y_displayed)
ValueError: zero-size array to reduction operation maximum which has no identity
从这些链接中,我不确定在我的 for 循环中在哪里实现 @Joe Kington 的掩码解决方案。
我现在正在使用此处提出的 @bernie 解决方案来获取给定 X 的 Y 值:
如何从图中提取点?
也许我可以 set_ylim() 手动给出该 X 处的最小和最大 Y 值?
如果有一种方法可以在定义的 xlim 中自动缩放作为标准 matplotlib 方法,那么这会容易得多