【问题标题】:How to automatically set ylim from data shown on the screen after setting xlim设置 xlim 后如何根据屏幕上显示的数据自动设置 ylim
【发布时间】:2023-03-03 19:24:02
【问题描述】:

比如我设置xlim后,ylim比屏幕上显示的数据点范围要宽。当然,我可以手动选择一个范围并设置它,但我更喜欢自动完成。

或者,至少,我们如何确定屏幕上显示的数据点的 y 范围?

在我设置 xlim 后立即绘制:

我手动设置 ylim 后的绘图:

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    这种方法适用于y(x) 是非线性的。给定您要绘制的数组 xy

    lims = gca().get_xlim()
    i = np.where( (x > lims[0]) &  (x < lims[1]) )[0]
    gca().set_ylim( y[i].min(), y[i].max() )
    show()
    

    【讨论】:

    • 感谢 Saullo,不过,autoscale(axis='y') 仍然会根据完整数据集计算数据范围,包括屏幕上未显示的数据点
    • 感谢您的反馈。我已经更新了y(x) 是非线性的情况的答案...
    【解决方案2】:

    要确定可以使用的 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[find_nearest(x, x_lims[0])] 和 y[find_nearest(x, x_lims[1])] 之间的最小值和最大值来找到 y_low 和 y_high,即: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().
    【解决方案3】:

    我发现@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() ) 
    

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 2015-08-30
      • 2021-07-01
      • 2012-06-12
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多