python - 如何更新子图?

标签 python matplotlib

我需要绘制许多图,查看它们并按“y”或“n”。我无法让 matplotlib 在循环中一一显示绘图。循环必须向我显示一个情节,然后我将按下某个按钮并重新开始。
我现在的代码是:

def press_event(event):
    answer = event.key
    if answer=='y':
        pass
    sys.stdout.flush()
    print(answer)
    
files = os.listdir(folder)

fig, ax = plt.subplots(14,2, figsize=(10,30))
fig.canvas.mpl_connect('key_press_event', press_event)
for file in files:
    target = file
    data = pd.read_csv(folder + target)
    fig.suptitle(target, fontsize=30)
    r = 0
    for key in data:
        sample = data[key]
        ts = [sample[i+1] - sample[i] for i in range(len(sample)-1)]
        decs,ts,point = cusum(sample,10)
        ax[r,0].plot(sample)
        ax[r,0].axvline(point,color='red')
        ax[r,1].plot(decs)
        ax[r,1].axvline(point, color='red')
        r += 1
    plt.show()
    fig.canvas.draw()
    plt.waitforbuttonpress()
    plt.pause(0.1)
    fig.clear()
现在它向我展示了第一个情节。我按下一个按钮,下一个窗口是空白的,内核崩溃了。

最佳答案

这是改编自 this画廊示例,使用 plt.waitforbuttonpress()

Blocking call to interact with the figure. Wait for user input and return True if a key was pressed, False if a mouse button was pressed and None if no input was given within timeout seconds. Negative values deactivate timeout.


只要您按下一个键,图形就会更新,如果您用鼠标单击,循环就会中断。
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(5, 2)

for i in range(10):
    x = np.random.random((5, 2, 100))

    for r, xx in enumerate(x):
        ax[r, 0].plot(xx[0], 'ro')
        ax[r, 1].plot(xx[1], 'bx')

    plt.show()
    fig.canvas.draw()
    if plt.waitforbuttonpress():  # True for key, False for mouse
        for axx in ax.flat:
            axx.clear()
    else:
        break
另一种可能性是使用 key_press_event .为此,您需要将绘图更新组合在一个单独的函数中并相应地调用它。
在这个例子中,我使用了 leftright键来切换数据。

import numpy as np
import matplotlib.pyplot as plt

n = 10
x = np.random.random((n, 5, 2, 100))
global i
i = 0

fig, ax = plt.subplots(5, 2)

def update(j):
    for axx in ax.flat:
        axx.clear()

    for r, xx in enumerate(x[j]):
        ax[r, 0].plot(xx[0], 'ro')
        ax[r, 1].plot(xx[1], 'bx')

def press_event(event):
    global i
    if event.key == 'left':
        i -= 1
    elif event.key == 'right':
        i += 1
    else:
        return
    i %= n
    update(i)

fig.canvas.mpl_connect('key_press_event', press_event)
update(0)

关于python - 如何更新子图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64208807/

相关文章:

python - 我可以使用 conda 安装 Python 的 alpha 或 beta 版本吗?

python - 计算 numpy 列表中项目的精确共现次数

python - 如何寻找趋势线并计算趋势线与 X 轴的斜率

python - 具有映射物理量的误差条和颜色的散点图

python - 类中定义的变量在 Python 3 中给出错误

python - Pandas - 将元组格式的 header 名称转换为字符串

python - 面向对象的 Python 与 Flask 服务器?

python - 如何删除 Matplotlib 烛台图表中的周末?

python - 如何使用 datetime.time 在 Python 中绘图

python - 克服空数组的 ValueError