Python 根据参数更改自动更新图形
我希望图形在参数值更改或定期更改时更新。我有以下代码:Python 根据参数更改自动更新图形,python,python-3.x,numpy,matplotlib,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=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更新时或定期运行时重新运行?因此,在这里,您应该了解如何正确使用numpy UFUNC,它在NDARRAY上运行,而不必在NDARRAY上循环: 其次,您必须有一个触发更新事件的位置,例如: 因为在这段代码中没有这样的例子,所以我假设您知道将在哪里发生。无论在哪里发生这种情况,都需要一个行句柄来更新数据 下面是一些示例代码,强调我认为您正在尝试做的事情:
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)
因此,这里有几件事,您应该了解如何正确使用numpy UFUNC,它在Ndarray上运行,而不必在Ndarray上循环: 其次,您必须有一个触发更新事件的位置,例如: 因为在这段代码中没有这样的例子,所以我假设您知道将在哪里发生。无论在哪里发生这种情况,都需要一个行句柄来更新数据 下面是一些示例代码,强调我认为您正在尝试做的事情:
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)
UFUNC是否比循环更有效?是的。除了代码更干净、更简洁之外,在计算上它可能要快一个数量级,如果不是更多的话,因为整个计算都在一个c函数调用中处理。事实上,在numpy数组上循环可能比在python列表中循环慢,因为在循环中进行的许多函数调用的开销ufuncs是否比循环更有效?是的。除了代码更干净、更简洁之外,在计算上它可能要快一个数量级,如果不是更多的话,因为整个计算都在一个c函数调用中处理。事实上,在numpy数组上循环可能比在python列表中循环要慢,这是因为在循环中会产生许多函数调用的开销