【问题标题】:Matplotlib - automated limits update [duplicate]Matplotlib - 自动限制更新
【发布时间】:2020-04-20 21:14:09
【问题描述】:

我想使用 matplotlib(pyplot.plotscattererrorbar)绘制一些点,使用 xlim 应用限制,然后调用一个函数来调整 Y 轴限制以匹配以自动方式可见的点。

MWE:

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(-10, 10)
plt.plot(x, x, 'ro')
plt.xlim(-5, 5)

plt.show()

当然,Y 轴限制大约是 (-11, 10),但我希望它们大约是。 (-5, 5)。我试过以下 matplotlib 函数: relimset_ylim(auto=True)autoscaleautoscale_view,它们都没有工作。我知道我可以记住所有绘制的点,将它们限制在给定的 X 值范围内,找到最小值和最大值,并在此基础上设置限制,但我正在寻找更简单的方法来做到这一点。

【问题讨论】:

  • 感谢@MadPhysicist。 DanHickstein 的This answer 正在工作。我很惊讶没有更简单的解决方案。下面的前两个答案不是我想做的。他们需要访问我试图避免的绘制数据。在我正在处理的代码中,这些数据是在不同的文件中生成的,传递这些参数很复杂。

标签: python matplotlib plot


【解决方案1】:

以下是您的预期结果吗?

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(-10, 10)
plt.plot(x, x, 'ro')
range_min = - 5
range_max = 5

plt.xlim(range_min, range_max)
plt.ylim(range_min, range_max)

plt.show()

【讨论】:

    【解决方案2】:

    您可以像这样屏蔽您的数据:

    x = np.arange(-10, 10)
    y = np.sin(3 * x) + 0.5 * x
    
    xmin = -5
    xmax = +5
    
    # compute ylim based on xlim and data
    selected = y[(x >= xmin) & (x <= xmax)]
    ymin = selected.min()
    ymax = selected.max()
    
    plt.plot(x, y, 'ro')
    plt.xlim(xmin xmax)
    plt.ylim(ymin, ymax)
    
    plt.show()
    

    matplotlib 要么为你做这件事,要么你自己做。后者用途广泛。

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 2023-03-13
      • 1970-01-01
      • 2014-12-09
      • 2012-04-22
      • 1970-01-01
      • 2013-02-06
      • 2021-11-10
      • 2013-01-08
      相关资源
      最近更新 更多