天天看点

python中图形交互_如何在matplotlib中以交互方式移动图形窗口?

尽管我仍然认为您应该使用bokeh,但我将告诉您如何使用matplotlib来实现它。在

它不能工作的问题是matplotlib的事件循环不是活动的,因此它不能消化窗口事件(比如close或resize)。不幸的是,它不可能从外部引发这种消化。您需要做的是使用matplotlib的动画系统。

实际上,您的代码已经为它做好了充分的准备,因此您可以使用FuncAnimation。在import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

import math

# generate data

x = [0.1*_a for _a in range(1000)]

y = map(lambda x : math.sin(x), x)

# don't need ion, we're using block=True (see end of code)

fig, ax = plt.subplots()

fig.show()

# ax = plt.gca()

lines, = ax.plot([], [])

# ax.set_ylim(-1, 1)

ax.grid()

MAX_N_DATA = 100

x_data = []

y_data = []

def showdata(i):

# New data received

x_data.append(x[i])

y_data.append(y[i])

# limit data length

if x_data.__len__() > MAX_N_DATA:

x_data.pop(0)

y_data.pop(0)

# Set Data

lines.set_xdata(x_data)

lines.set_ydata(y_data)

# The data limits are not updated automatically.

ax.relim()

# with tight True, graph flows smoothly.

ax.autoscale_view(tight=True, scalex=True, scaley=True)

# draw will be called by the animation system

# instead of time.sleep(0.01) we use an update interval of 10ms

# which has the same effect

anim = FuncAnimation(fig, showdata, range(len(x)), interval=10, repeat=False)

# start eventloop

plt.show(block=True)