Carlos Carvalho
Carlos Carvalho

Reputation: 107

How create a simple animated graph with matplotlib from a dataframe

Someone can help me to correct the code below to visualize this data with animated matplotlib?

The dataset for X and Y axis are describe below.

X- Range
    mydata.iloc[:,[4]].head(10)

       Min_pred
    0  1.699189
    1  0.439975
    2  2.989244
    3  2.892075
    4  2.221990
    5  3.456261
    6  2.909323
    7 -0.474667
    8 -1.629343
    9  2.283976

    Y - range
    dataset_meteo.iloc[:,[2]].head(10)
    Out[122]: 
       Min
    0  0.0
    1 -1.0
    2  2.0
    3 -2.0
    4 -4.0
    5 -4.0
    6 -5.0
    7 -7.0
    8 -3.0
    9 -1.0

I've tried the code below,

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

d = pd.read_excel("mydata.xls")
x = np.array(d.index)
y = np.array(d.iloc[:,[2]])
mydata = pd.DataFrame(y,x)

fig = plt.figure(figsize=(10,6))
plt.xlim(1999, 2016)
plt.ylim(np.min(x), np.max(x))
plt.xlabel('Year',fontsize=20)
plt.ylabel(title,fontsize=20)
plt.title('Meteo Paris',fontsize=20)

def animate(i):
    data = mydata.iloc[:int(i+1)] #select data range
    p = sns.lineplot(x=data.index, y=data[title], data=data, color="r")
    p.tick_params(labelsize=17)
    plt.setp(p.lines,linewidth=7)
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=17, repeat=True)

The idea is to create a graph where the predicted (Y) would be animated kind a same like this one in the link below. https://www.courspython.com/animation-matplotlib.html

Thanks if you can help

Upvotes: 1

Views: 189

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40737

Is this what you are trying to get?

x = np.arange(1999,2017)
y = np.random.random(size=x.shape)

fig = plt.figure(figsize=(4,3))
plt.xlim(1999, 2016)
plt.ylim(np.min(y), np.max(y))
plt.xlabel('Year',fontsize=20)
plt.ylabel('Y',fontsize=20)
plt.title('Meteo Paris',fontsize=20)
plt.tick_params(labelsize=17)

line, = plt.plot([],[],'r-',lw=7)

def animate(i):
    x_, y_ = x[:i+1],y[:i+1]
    line.set_data(x_,y_)
    return line,

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(x), repeat=True)

enter image description here

Upvotes: 2

Related Questions