根据参数更改自动更新图表

时间:2017-06-20 00:18:11

标签: python python-3.x numpy matplotlib

我希望在更改参数值或定期更新图表时更新。我有以下代码:

a=0`
b=50
c=100

def sine(x,y,l):
    A=numpy.zeros(l)
    for i in range(l):
        A[i]=numpy.sin(2*math.pi*(i+x)/y)
    return A


def plot(l):
    matplotlib.pyplot.clf()
    matplotlib.pyplot.plot(l)

plot(sine(a,b,c))`

`

每次更新a / b / c或定期更新时,如何让绘图功能重新运行?

1 个答案:

答案 0 :(得分:2)

这里有一些事情,你应该学习正确使用numpy ufuncs,它们在ndarrays上运行而不必遍历它们:

https://docs.scipy.org/doc/numpy-1.12.0/reference/ufuncs.html

其次,您必须有一个触发更新事件的地方,例如:

http://openbookproject.net/thinkcs/python/english3e/events.html

由于此代码中没有此类示例,我将假设您知道将要发生的位置。无论发生什么,那么您需要一个线的句柄来更新数据。

https://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_xdata https://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_ydata

以下是一些示例代码,突出显示了我认为您正在尝试做的事情:

import numpy as np
import matplotlib.pyplot as plt

l = 100
x = np.linspace(0, 2 * np.pi, l)
y = np.sin(x)

fig, ax = plt.subplots(1, 1)  # generate figure and axes objects so that we have handles for them
curve = ax.plot(x, y)[0]  # capture the handle for the lines object so we can update its data later

# now some kind of event happens where the data is changed, and we update the plot
y = np.cos(x)  # the data is changed!
curve.set_ydata(y)

# necessary if you are just executing this as a script
# this example is a little more clear if executed stepwise in ipython
plt.show(block=True)