【问题标题】:How to make matplotlib auto scale y axis when using the draw_artist?使用draw_artist时如何使matplotlib自动缩放y轴?
【发布时间】:2021-10-02 18:47:33
【问题描述】:

我有以下示例代码:

import matplotlib.pyplot as plt

# start with zeroed data

data_points = 10

fig, axs = plt.subplots()
x = list(range(data_points))
y = [0] * data_points
line, = axs.plot(x, y)

# initial render is required
fig.canvas.draw()

for i in range(10):
    y.pop(0)
    y.append(i / 10)

    line.set_ydata(y)
    axs.draw_artist(axs.patch)
    axs.draw_artist(line)

    fig.canvas.draw()

plt.show()

这模拟了我在我的应用程序中所做的事情:我有一个归零的数据集,然后我将值附加到 y 数据并使用 draw_artist 重绘。

我在这里看到最终结果是我在实际应用中得到的结果:Y 轴被缩放以适应附加到 y 的数据:

Y 最终应该从 0 变为 0.9,但它停留在数据第一次被归零时的样子。

如何在上面的示例中正确更新 y 轴?

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    这里是你的代码的更新版本,你可以通过定义 ylim 来实现。

    import matplotlib.pyplot as plt
    import numpy as np
    
    # start with zeroed data
    
    data_points = 10
    
    fig, axs = plt.subplots()
    x = list(range(data_points))
    y = [0] * data_points
    line, = axs.plot(x, y)
    
    # initial render is required
    fig.canvas.draw()
    
    for i in range(10):
        y.pop(0)
        y.append(i / 10)
    
        line.set_ydata(y)
        axs.draw_artist(axs.patch)
        axs.draw_artist(line)
    
        fig.canvas.draw()
    plt.ylim(np.min(y),np.max(y))
    
    plt.show()
    

    这是你将得到的:

    【讨论】:

    • 啊,很好,我认为 matplotlib 自动缩放,我只是错过了一些电话。但这是有道理的,同样简单 - 谢谢!
    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2015-06-10
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多