2016-06-17 179 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