简体   繁体   中英

Funcanimation is not animating line Graph/time series from fixed excel file?

I am trying to animate the time series using Python with an excel file. Data looks like:

在此处输入图像描述

However, it is not animating the fixed graph, only stored the graph in gif format:

import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

index = count()


def animate(i):
    data = pd.read_excel(r'D:\new result\Results\SCA\all_inone_final.xlsx')
    x = data['Date']
    y1 = data['LAC']
    y2 = data['GAC']

    plt.cla()

    plt.plot(x, y1, label='LAC')
    plt.plot(x, y2, label='GAC')

    plt.legend(loc='upper left')
    plt.tight_layout()


ani = FuncAnimation(plt.gcf(), animate, interval=100000)
ani.save(r'D:\new result\Results\SCA\live_plots\_'+'_SCA_4.gif', writer='imagemagick')
plt.tight_layout()
plt.show()

any recommendation help? TIA

Check this code:

# import section
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from datetime import datetime, timedelta
plt.style.use('fivethirtyeight')

# dataframe creation section
N = 400
Date = [datetime.strptime('Jan 1 2002', '%b %d %Y') + timedelta(days = x) for x in range(N)]
x = np.linspace(0, N/10, N)
LAC = np.sin(3*x) * np.cos(6*x)
GAC = np.cos(x) * np.cos(5*x)

data = pd.DataFrame({'Date': Date,
                     'LAC': LAC,
                     'GAC': GAC})

# figure preparation section
fig, ax = plt.subplots(1, 1, figsize = (16, 8))

# animate function definition section
# note the use of i
velocity = 1
span = 7
def animate(i):
    plt.cla()

    x = data['Date'][velocity*i : span + velocity*i]
    y1 = data['LAC'][velocity*i : span + velocity*i]
    y2 = data['GAC'][velocity*i : span + velocity*i]

    ax.plot(x, y1, label='LAC')
    plt.plot(x, y2, label='GAC')

    ax.legend(loc='upper left')
    ax.set_ylim([-2, 2])
    plt.tight_layout()

# animation function call
ani = FuncAnimation(fig, animate, interval = 1, frames = N-span)
plt.show()

which give this result:

在此处输入图像描述

Since I do not have access to you data source, in the "dataframe creation section" I create a dataframe in order to perform the animation, you have to replace it with your data.
Note the use of i in the animate function: I used it to slice the x , y1 and y2 arrays in order to plot only a portion of span elements long. As animation is going on, the i increases, so the slice of the arrays flows along them and the plot shows the trend of y1 and y2 over time.
I do not know if this is what you want, because you did not specify what you want to see changing while the animation is going on, however I hope this code could help you to understand how to create one.


EDIT

This the code with your data:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')

data = pd.read_excel('data_comparison.xlsx')
velocity = 1
span = 7

fig, ax = plt.subplots(1, 1, figsize = (16, 8))

def animate(i):
    plt.cla()

    x = data['Date'][velocity*i : span + velocity*i]
    y1 = data['LAC'][velocity*i : span + velocity*i]
    y2 = data['GAC'][velocity*i : span + velocity*i]

    ax.plot(x, y1, label='LAC')
    plt.plot(x, y2, label='GAC')

    ax.legend(loc='upper left')
    ax.set_ylim([0, 65])
    plt.tight_layout()

ani = FuncAnimation(fig, animate, interval = 1, frames = len(data)-span)
plt.show()

which gives this animation:

在此处输入图像描述

(I cut the animation because its size is too big, over 2 MB. However you can run the code above and you will get the same animation)


EDIT 2

Fixed x axis:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')

data = pd.read_excel('data_comparison.xlsx')
velocity = 1
span = 1

fig, ax = plt.subplots(1, 1, figsize = (16, 8))

def animate(i):
    plt.cla()

    x = data['Date'][0 : span + velocity*i]
    y1 = data['LAC'][0 : span + velocity*i]
    y2 = data['GAC'][0 : span + velocity*i]

    ax.plot(x, y1, label='LAC')
    plt.plot(x, y2, label='GAC')

    ax.legend(loc='upper left')
    ax.set_xlim([data['Date'].iloc[0], data['Date'].iloc[-1]])
    ax.set_ylim([0, 65])
    plt.tight_layout()

ani = FuncAnimation(fig, animate, interval = 1, frames = len(data)-span)
ani.save('animation.gif', writer = 'imagemagick')
plt.show()

在此处输入图像描述

You can slice the arrays with [0: span + velocity*i] : the start is fixed while the end changes as animation goes on. To fix the axes I used this lines:

    ax.set_xlim([data['Date'].iloc[0], data['Date'].iloc[-1]])
    ax.set_ylim([0, 65])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM