【问题标题】:Simple animation of 2D coordinates using matplotlib and pyplot使用 matplotlib 和 pyplot 的 2D 坐标的简单动画
【发布时间】:2012-06-09 09:31:23
【问题描述】:

我是 matplotlib 的新手。我有一个 x-y 坐标列表,我在 python 中更新并希望使用 matplotlib 的 pyplot 进行动画处理。我想提前指定 x 范围和 y 范围。以下是我当前的代码:

import matplotlib.pyplot as plt
x=[1,2,3,4]
y=[5,6,7,8]
for t in range(100):
    #lists x and y get updated here
    #...
plt.plot(x, y, marker='o', linestyle='None')
plt.show()

如您所见,我使用plt.plot()plt.show() 在我的迭代循环结束时 仅绘制最终坐标。但我想将此步骤置于循环中,并在每次迭代时以指定的暂停时间进行绘图,以便在循环运行时获得动画。

只是在循环内移动该语句或对其进行调整是行不通的。 不过,我想保持它非常简单,并且不想使用matplotlib.animation。有没有一些不使用更多模块和库的简单方法(只有 plt.pause() 之类的东西,也许只有更多)可以让我做我想做的事?

我在网上看了很多地方,大多数方法遇到的问题是我在 Windows 上使用 python(x,y) (即 python 版本 2.7),并且使用过于复杂的模块和库的动画是在这里崩溃。

但是,我可以在 matplotlib 站点上运行像 this example 这样的简单内容,这与我想要的很接近,但并不完全。所以也许最好的事情是修改这个例子,适用于我的二维数据情况(这个例子是一维行)。但欢迎提出任何其他建议。

【问题讨论】:

    标签: python animation python-2.7 matplotlib


    【解决方案1】:

    本文改编自animation demo

    import matplotlib.pyplot as plt 
    import numpy as np
    
    fig, ax = plt.subplots()
    
    x = [1, 2, 3, 4]
    y = [5, 6, 7, 8]
    
    for t in range(10):
        if t == 0:
            points, = ax.plot(x, y, marker='o', linestyle='None')
            ax.set_xlim(0, 10) 
            ax.set_ylim(0, 10) 
        else:
            new_x = np.random.randint(10, size=5)
            new_y = np.random.randint(10, size=5)
            points.set_data(new_x, new_y)
        plt.pause(0.5)
    

    虽然这很简单,但文档字符串说它很慢。

    【讨论】:

    • +1。这行得通。我将尝试将其调整到我的最终程序中,看看效果如何。
    • 使用ax.clear()可能会比较方便;那么你可以简单地绘制一个新的数字,你不需要区分第一次和以后的运行。另外,plt.pause() 对我造成了错误,我改用了fig.canvas.start_event_loop()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 2013-12-24
    相关资源
    最近更新 更多