2016-06-17 183 views
0

我试图用matplotlib创建一个动画,以在一个动画中同时绘制几个数据集。 问题是我的两个数据集中有50个点,第三个数据点有70000个点。因此,同时绘图(点之间具有相同的间隔)是无用的,因为前两个数据集在第三个数据集开始显示时进行绘图。python matplotlib多行动画

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

请参阅代码如下随机数据:

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

但有一点是可以同时获得动画(但以不同的速度)画线。

回答

0

比使用单独的动画调用更简单的是更新同一动画调用中的所有行,但速度不同。在你的情况下,只需每隔(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

+0

谢谢!有用! – MVab