matplotlib作为打印服务器



通过分离服务器和客户端进程,服务器将始终提供绘图服务,以便您始终可以看到它。

matplotlib的tk窗口(plt.show(((仅在第一次运行,然后仅在外部客户端程序请求时更新数据,并将其显示在现有窗口中。

问题:

  1. 对于不同的客户端请求,无法在服务器上的同一tk窗口内更新绘图。

  2. 如果用户没有关闭窗口,则不会出现下一个函数调用。

下面的代码是我的测试代码,我该如何解决这个问题?

run_once = 0
# make a figure + axes
fig, ax = plt.subplots(1, 1, tight_layout=True)

im = None
def show_grid(np_array):
global run_once, im
array_shape = np_array.shape
x = array_shape[0]
y = array_shape[1]
if run_once == 0:
run_once = 1
print('client A request')
# make a figure + axes
# fig, ax = plt.subplots(1, 1, tight_layout=True)
# make color map
my_cmap = clr.ListedColormap(['#000000', '#0074D9', '#FF4136', '#2ECC40', '#FFDC00', '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])
# set the 'bad' values (nan) to be white and transparent
my_cmap.set_bad(color='w', alpha=0)
bound = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
my_norm = clr.BoundaryNorm(bound, my_cmap.N, clip=True)
# # draw the grid
for i in range(x + 1):
ax.axhline(i, lw=2, color='k', zorder=5)
for j in range(y + 1):
ax.axvline(j, lw=2, color='k', zorder=5)
# draw the boxes
im = ax.imshow(np_array, interpolation='none', cmap=my_cmap, norm=my_norm, extent=[0, y, 0, x], zorder=0)
# turn off the axis labels
ax.axis('off')
plt.show()
# plt.pause(0.0001)
# plt.clf()
else:
print('client B request')
im.set_array(np_array)
fig.canvas.draw()
fig.canvas.flush_events()

修复了我的代码错误,你可以在这里找到工作版本

固定点是:

plt.ion()

if run_once == 0:
run_once = 1
print('client A request')
# make a figure + axes
# fig, ax = plt.subplots(1, 1, tight_layout=True)
fig.show()
fig.canvas.draw()
fig.canvas.flush_events()
plt.show()
else:
print('client B, C, D, ... request')
# im.set_array(np_array.ravel())
im.set_array(np_array)
fig.show()
fig.canvas.draw()
fig.canvas.flush_events()
plt.draw()

最新更新