【发布时间】:2023-03-03 19:24:02
【问题描述】:
比如我设置xlim后,ylim比屏幕上显示的数据点范围要宽。当然,我可以手动选择一个范围并设置它,但我更喜欢自动完成。
或者,至少,我们如何确定屏幕上显示的数据点的 y 范围?
在我设置 xlim 后立即绘制:
我手动设置 ylim 后的绘图:
【问题讨论】:
标签: python matplotlib plot
比如我设置xlim后,ylim比屏幕上显示的数据点范围要宽。当然,我可以手动选择一个范围并设置它,但我更喜欢自动完成。
或者,至少,我们如何确定屏幕上显示的数据点的 y 范围?
在我设置 xlim 后立即绘制:
我手动设置 ylim 后的绘图:
【问题讨论】:
标签: python matplotlib plot
这种方法适用于y(x) 是非线性的。给定您要绘制的数组 x 和 y:
lims = gca().get_xlim()
i = np.where( (x > lims[0]) & (x < lims[1]) )[0]
gca().set_ylim( y[i].min(), y[i].max() )
show()
【讨论】:
y(x) 是非线性的情况的答案...
要确定可以使用的 y 范围
ax = plt.subplot(111)
ax.plot(x, y)
y_lims = ax.get_ylim()
这将返回当前 y 限制的元组。
但是,您可能需要通过在 x 限制处找到 y 数据的值来自动设置 y 限制。有很多方法可以做到这一点,我的建议是:
import matplotlib.pylab as plt
ax = plt.subplot(111)
x = plt.linspace(0, 10, 1000)
y = 0.5 * x
ax.plot(x, y)
x_lims = (2, 4)
ax.set_xlim(x_lims)
# Manually find y minimum at x_lims[0]
y_low = y[find_nearest(x, x_lims[0])]
y_high = y[find_nearest(x, x_lims[1])]
ax.set_ylim(y_low, y_high)
函数在哪里归功于unutbu in this post
import numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx
但是,当数据 y 数据不是线性时,这会出现问题。
【讨论】:
y_low = y[find_nearest(x, x_lims[0]):find_nearest(x, x_lims[1])].min() y_high = y[find_nearest(x, x_lims[0]):find_nearest(x, x_lims[1])].max().
我发现@Saullo Castro 的回答很有用,并略有改进。您可能想要调整限制许多不同的图。
import numpy as np
def correct_limit(ax, x, y):
# ax: axes object handle
# x: data for entire x-axes
# y: data for entire y-axes
# assumption: you have already set the x-limit as desired
lims = ax.get_xlim()
i = np.where( (x > lims[0]) & (x < lims[1]) )[0]
ax.set_ylim( y[i].min(), y[i].max() )
【讨论】: