I've tried to create an animation using Matplotlib, it seems to be animating correctly but it's not showing all the data points in the dataset. Its a time series from Jan 2020 to Dec 2021 - it seems to be animating to 2020-06 only right now.
Below is the entire code
import yfinance as yf
import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Get data
data = yf.download('TSLA',start='2020-01-01')
df = data['Adj Close'].to_frame()
fig = plt.figure()
plt.ylabel('Stock Price')
plt.xlabel('Date')
def buildchart(i=int):
plt.legend(df.columns)
p = plt.plot(df[:i].index, df[:i].values, color = 'black')
import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, buildchart, interval = 100)
import os
f = os.getcwd() '/animation.mp4'
writervideo = ani.FFMpegWriter(fps=30)
animator.save(f, writer=writervideo, dpi= 300)
CodePudding user response:
The basic form of the animation is to set the empty graph type and the x-axis and y-axis ranges, and then update the data with the animation function. It is rewritten in an object-oriented way because it is easy to set up the details. The animation is set to repeat for a number of records in a number of frames.
import yfinance as yf
import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Get data
data = yf.download('TSLA',start='2020-01-01')
df = data['Adj Close'].to_frame()
fig,ax = plt.subplots()
line, = ax.plot([], [], color='k', lw=3)
ax.set(xlim=(df.index[0], df.index[-1]), ylim=(df['Adj Close'].min(), df['Adj Close'].max()))
ax.set_ylabel('Stock Price')
ax.set_xlabel('Date')
def buildchart(i):
line.set_data(df[:i].index, df[:i]['Adj Close'])
ax.legend(df.columns)
anim = ani.FuncAnimation(fig, buildchart, frames=len(df), interval=100)
plt.show()