python - 在数组中定义多个绘图对象并在 matplotlib 动画中更新

标签 python matplotlib plot

我遵循了以下问题的答案

Defining multiple plots to be animated with a for loop in matplotlib

答案定义并绘制线条,但我想绘制并更新动画中的点。我修改了代码并尝试绘制这些点。当我运行代码时,它显示空白图形,没有绘制任何内容。

from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np

fig = plt.figure()

ax = plt.axes(xlim=(-10, 10), ylim=(0, 100))

N = 4
points = ax.plot( *([[], []]*N) )

def init():    
    for line in points:
        line.set_data([], [])
    return points

def animate(i):
    # for j,line in enumerate(lines):
    #   print j,i
    #     line.set_data([0,j], [2,i])
    points[0].set_data([[0],[i]])
    points[1].set_data([[1],[i+1]])
    points[2].set_data([[2],[i+2]])
    points[3].set_data([[3],[i+3]])
    return points

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

plt.show()

我该如何解决这个问题?

谢谢

最佳答案

set_data()函数在绘制一条线时需要至少包含 2 个元素的列表。

例如:

def animate(i):
    points[0].set_data([[0, 1],[i, i+1]])
    points[1].set_data([[1, 2],[i+1, i+2]])
    points[2].set_data([[2, 3],[i+2, i+3]])
    points[3].set_data([[3, 4],[i+3, i+4]])
    return points

只需使点可见,因为我们放置了一个标记:

points = ax.plot( *([[], []]*N), marker="o")

完整代码:

fig = plt.figure()

ax = plt.axes(xlim=(-10, 10), ylim=(0, 100))

N = 4
points = ax.plot( *([[], []]*N), marker="o")

def init():    
    for line in points:
        line.set_data([], [])
    return points

def animate(i):
    points[0].set_data([0],[i])
    points[1].set_data([[1],[i+1]])
    points[2].set_data([[2],[i+2]])
    points[3].set_data([[3],[i+3]])
    return points

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

plt.show()

enter image description here

关于python - 在数组中定义多个绘图对象并在 matplotlib 动画中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45515563/

相关文章:

Python Pandas - 重命名列后出现段错误?

python - 在函数内动态更改全局变量值

Python Selenium 超时异常捕获

python - 保存的图形和显示的图形之间的差异

python - 如何使用 matplotlib 绘制 collections.Counter 直方图?

python - 在 matplotlib 中缩放轴 3d

python - 这个编码是什么以及如何转换它?

python - 从一个 python 文件调用多个绘图函数时出现问题

python - 在 Python 中使用 matplotlib.animation 的动画 3D 条形图示例

python - 如何从绘图中完全删除 x 轴(和 y 轴)并使用 Python 或 R 编程在某些点绘制切线?