Matplotlib: Plot something new in an axis upon key press

人走茶凉 提交于 2021-01-28 19:06:46

问题


Each time the user presses a key on the keyboard, a new plot should be drawn. The example below uses just a random plot, in reality, I'll combine it with a statemachine that calls a different plot() function on each press.

I have the short minimal code with a random plot:

fig = plt.figure(1)
ax1 = fig.add_subplot(111, aspect='equal')

def plot(e):
    ax1.cla()
    ax1.plot(np.random.rand(10))

cid = fig.canvas.mpl_connect('key_press_event', plot)

plt.show()

Unfortunately, nothing happens. What is missing or how could I fix it? I guess I have to somehow redraw the ax1 or then I completely missunderstand something...


回答1:


This is my code, I figured it has to do with the plt.figure(1), because if I do that in the plot method it does generate a new graph everytime I press a key.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(1)
ax1 = fig.add_subplot(111, aspect='equal')

def plot(e):
    fig = plt.figure(1)
    ax1 = fig.add_subplot(111, aspect='equal')
    ax1.cla()
    ax1.plot(np.random.rand(10))

cid = fig.canvas.mpl_connect('key_press_event', plot)

plt.show()



回答2:


add following line to the function:

fig.canvas.draw_idle()


来源:https://stackoverflow.com/questions/38396318/matplotlib-plot-something-new-in-an-axis-upon-key-press

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!