问题
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