Display changing matrix on every cycle with user i

2019-08-16 01:35发布

I have a python script where I want to display a new random matrix, in the present window like a video stream, every time a user inputs the character 'p'

import pylab as plt
plt.figure()

matrix = np.zeros((size[0],size[1]))
plt.matshow(matrix)
plt.show()

while(1):
 cmd = raw_input('...')

 if(raw_input == 'p'):
  matrix = get_rand_mat()

 plt.matshow(matrix)
 plt.show()

Where get_rand_mat is some arbitary function which returns a matrix of the correct dimensions

But the big problem here is that I have to close the figure window everytime I want to get new user input and then display the updated matrix.

How can I update the displayed matrix per user input iteration and without having to close a window for the program to progress?

1条回答
ら.Afraid
2楼-- · 2019-08-16 02:04

Since the matplotlib plotting window takes over the event loop, the input from the console is not possible while the window is open.

While it would be possible to use interactive mode (plt.ion()), this might cause other issues. So my suggestion would be to completely work within one existing figure and connect an event to the key press of p.

import matplotlib.pyplot as plt
import numpy as np

size= (25,25)
get_rand_mat = lambda : np.random.rand(*size)

fig = plt.figure()

matrix = np.zeros((size[0],size[1]))
mat = plt.matshow(matrix, fignum=0, vmin=0, vmax=1)

def update(event):
    if event.key == "p":
        matrix = get_rand_mat()
        mat.set_data(matrix)
        fig.canvas.draw_idle()

fig.canvas.mpl_connect("key_press_event", update)

plt.show()

If you run the above and press p, a new random matrix is shown within the existing figure.

查看更多
登录 后发表回答