【问题标题】:python matplotlib multiple lines animationpython matplotlib多行动画
【发布时间】:2016-06-17 10:13:22
【问题描述】:

我正在尝试使用 matplotlib 创建一个动画,以便在一个动画中同时绘制多个数据集。 问题是我的两个数据集有 50 个点,第三个有 70000 个点。因此,同时绘制(点之间的间隔相同)是没有用的,因为前两个数据集在第三个数据集刚刚开始显示时就完成了绘制。

因此,我试图让数据集在单独的动画调用中进行绘图(具有不同的间隔,即绘图速度),但在一个绘图上。问题是动画只显示最后一个调用的数据集。

请看下面随机数据的代码:

import numpy as np
from matplotlib.pyplot import *
import matplotlib.animation as animation
import random

dataA = np.random.uniform(0.0001, 0.20, 70000)
dataB = np.random.uniform(0.90, 1.0, 50)
dataC = np.random.uniform(0.10, 0.30, 50)

fig, ax1 = subplots(figsize=(7,5))

# setting the axes
x1 = np.arange(0, len(dataA), 1)
ax1.set_ylabel('Percentage %')
for tl in ax1.get_xticklabels():
    tl.set_color('b')

ax2 = ax1.twiny()
x2 = np.arange(0, len(dataC), 1)
for tl in ax2.get_xticklabels():
    tl.set_color('r')

ax3 = ax1.twiny()
x3 = np.arange(0, len(dataB), 1)
for tl in ax3.get_xticklabels():
    tl.set_color('g')

# set plots
line1, =ax1.plot(x1,dataA, 'b-', label="dataA")
line2, =ax2.plot(x2,dataC, 'r-',label="dataB")
line3, =ax3.plot(x3, dataB, 'g-', label="dataC")

# set legends
ax1.legend([line1, line2, line3], [line1.get_label(),line2.get_label(), line3.get_label()])

def update(num, x, y, line):
    line.set_data(x[:num], y[:num])
    line.axes.axis([0, len(y), 0, 1]) #[xmin, xmax, ymin, ymax]
    return line, 


ani = animation.FuncAnimation(fig, update, len(x1), fargs=[x3, dataB, line3],interval=150,  blit=True, repeat=False)

ani = animation.FuncAnimation(fig, update, len(x1), fargs=[x1, dataA, line1],interval=5,  blit=True, repeat=False)

ani = animation.FuncAnimation(fig, update, len(x1), fargs=[x2, dataC, line2],interval=150,  blit=True, repeat=False)

# if the first two 'ani' are commented out, it live plots the last one, while the other two are plotted static

show()

最后的情节应该是这样的: http://i.imgur.com/RjgVYxr.png

但关键是让动画同时(但以不同的速度)绘制线条。

【问题讨论】:

    标签: python animation matplotlib plot


    【解决方案1】:

    比使用单独的动画调用更简单的是在同一个动画调用中更新所有线条,但速度不同。在您的情况下,仅在每 (70000/50) 次调用 update 时更新红线和绿线。

    您可以通过将您的代码从您的 update 函数开始更改为以下内容:

    def update(num):
        ratio = 70000/50
        i = num/ratio
        line1.set_data(x1[:num], dataA[:num])
        if num % ratio == 0:
            line2.set_data(x2[:i], dataC[:i])
            line3.set_data(x3[:i], dataB[:i])
    
    
    ani = animation.FuncAnimation(fig, update, interval=5, repeat=False)
    
    show()
    

    注意if num % ratio == 0 语句,如果 num 可以被比率整除,它只会执行以下行。此外,您需要为更新较慢的行创建一个单独的计数器。在这种情况下,我使用了i

    【讨论】:

      猜你喜欢
      • 2014-05-27
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多