【问题标题】:Matplotlib.animation: display points after plotting?Matplotlib.animation:绘图后显示点?
【发布时间】:2014-01-02 11:26:42
【问题描述】:

我正在阅读 Jake Vanderplas 的优秀代码,用于绘制沿正弦曲线移动的点:

"""
This short code snippet utilizes the new animation package in
matplotlib 1.1.0; it's the shortest snippet that I know of that can
produce an animated plot in python. I'm still hoping that the
animate package's syntax can be simplified further. 
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def simData():
# this function is called as the argument for
# the simPoints function. This function contains
# (or defines) and iterator---a device that computes
# a value, passes it back to the main program, and then
# returns to exactly where it left off in the function upon the
# next call. I believe that one has to use this method to animate
# a function using the matplotlib animation package.
#
    t_max = 10.0
    dt = 0.05
    x = 0.0
    t = 0.0
    while t < t_max:
        x = np.sin(np.pi*t)
        t = t + dt
        yield x, t

def simPoints(simData):
    x, t = simData[0], simData[1]
    time_text.set_text(time_template%(t))
    line.set_data(t, x)
    return line, time_text

##
##   set up figure for plotting:
##
fig = plt.figure()
ax = fig.add_subplot(111)
# I'm still unfamiliar with the following line of code:
line, = ax.plot([], [], 'bo', ms=10)
ax.set_ylim(-1, 1)
ax.set_xlim(0, 10)
##
time_template = 'Time = %.1f s'    # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
## Now call the animation package: (simData is the user function
## serving as the argument for simPoints):
ani = animation.FuncAnimation(fig, simPoints, simData, blit=False,\
     interval=10, repeat=True)
plt.show()

您将如何修改此代码以使每个点(即 x、y 的计算值)在绘制后仍保留在图形上?因此,在动画快结束时,您会看到所有先前的点形成正弦曲线。

【问题讨论】:

  • 其实我明白了!我正在修改stackoverflow.com/questions/16842770/… 中的部分,其中 xdata、ydata 是在函数外部定义的(如 []、[]),而绘制它们的函数只是将新数据附加到 xdata、ydata 中。

标签: python matplotlib


【解决方案1】:

查看此链接以了解以下说明:

# I'm still unfamiliar with the following line of code:
line, = ax.plot([], [], 'bo', ms=10)

Python code. Is it comma operator?


此外,这可能对您的绘图问题没有帮助,但您似乎正在定义 time_template 但随后不使用该定义,除非在脚本中的该点之后全局调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2017-04-16
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多