0

I am using the following code to animate a line chart from a CSV file that has two columns - which would look like a list of dates and closing stock prices. I would like to add axis labels and a chart title to the sub plot, but I am unable to make them appear. I would also like to hold my axes constant by fixing the x and y limits. Am I doing my parameters in the wrong block of code?

The code I have is as follows:

%matplotlib notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import animation
from matplotlib.animation import FuncAnimation


dfCsvf=pd.read_csv("ctmxf.csv", header=0, parse_dates=['Date'])
dfCsv=pd.read_csv("ctmxnew.csv", header=0, parse_dates=['Date'])


plt.style.use('seaborn')
fig = plt.figure(figsize=(8,8))
ax=fig.add_subplot(1,1,1)
ax.title.set_text('CTMX Historical Share Price')
ax.set_xlabel('Date')
ax.set_ylabel('CTMX Share Price')
ax.set_xlim(dfCsv['Date'].iloc[0], dfCsv['Date'].iloc[-1])
ax.set_ylim(0, 35)

def animate(i):
    ctmxStock=pd.read_csv("ctmxnew.csv", header=0, parse_dates=['Date'])
    x=[]
    y=[]

    x = ctmxStock[0:i]['Date']
    y = ctmxStock[0:i]['Close']

    ax.clear()
    ax.plot(x,y)

animation = FuncAnimation(fig, func=animate, interval=10, blit=True)
plt.show()

plt.rcParams['animation.convert_path'] ="C:\Program Files\ImageMagick-7.1.0-Q16-HDRI\magick.exe"
animation.save(r'C:\Users\hchan009\anim.gif', writer='imagemagick', extra_args="convert", fps=60)

Thanks for any help you may be able to provide.

Ian Chan
  • 1
  • 1
  • 1
    Probably, when you use ax.clear() , it clears also your labels which you delared above. Try to set x and y labels inside animate function. – Raxodius Jun 24 '21 at 09:06
  • 1
    another option is, rather than clearing the axes inside the animate function, to add a line2D instance to the axes outside the function, and the use `line.set_data(x, y)` inside the function. For some examples, see [here](https://matplotlib.org/stable/gallery/animation/animate_decay.html#sphx-glr-gallery-animation-animate-decay-py) or [here](https://matplotlib.org/stable/gallery/animation/simple_anim.html#sphx-glr-gallery-animation-simple-anim-py) – tmdavison Jun 24 '21 at 09:38

0 Answers0