Home > Net >  How can I get dates on the x axis in my animated line chart?
How can I get dates on the x axis in my animated line chart?

Time:03-25

I borrowed some code from the web for this line chart animation, but unfortunately it came with some sort of count() for the x axis rather than the dates that I am importing from Yahoo. I'm new to this, can you help?

I get an okay plot, but I would rather have dates under the x axis.

import pandas_datareader.data as web
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
from pylab import legend
from matplotlib import animation
from matplotlib.animation import FuncAnimation
from itertools import count


plt.style.use('ggplot')
fig, axes = plt.subplots(nrows = 1, ncols = 1, figsize = (12,5))


# set up investment choice and start/end dates
choice = str(input('Please enter your investment symbol: '))
start = str(input('Please enter your comparison starting date(mm/dd/yyyy):'))
end = dt.date.today()
symbol = '^GSPC', choice #S&P500 symbol and your choice for comparison

# source of data and method of acqusition of data
source = 'yahoo'            
data = web.DataReader(symbol, source, start, end)['Adj Close']

#adjust data shares for even start:
numer = data.iat[0,0]
denom = data.iat[0,1]  #call starting date value for chosen symbol
shares = numer/denom #compute number of shares for even start  

data[choice] = shares*(pd.DataFrame(data[choice])) #Shares*share price
                                                    #for entire choice column
                                                   #for comparisons
for i in range(0, len(data)):  #set up animation steps
    l1 = data['^GSPC']
    l2 = data[choice]

x1,y1,y2,y3 = [], [], [], []
xval = count(0,1.37)


print(l1, l2)

def animate(i):
    x1.append(next(xval))
    y1.append((l1[i]))
    y2.append((l2[i]))

    axes.plot(x1,y1, color="red")
    axes.plot(x1,y2, color="blue")   
    

if __name__ == '__main__':
    try:
        anim = FuncAnimation(fig, animate, interval=1)                                         
        #plt.plot(data)
        plt.xlabel('Days')
        plt.ylabel('Dollars')
        plt.title('The S&P500 (red) vs. Your Investment (blue),'
              ' Using Adjusted Share Amounts for Even Start')
        #legend(['S&P500', choice])
        plt.show()
        
    except IndexError as e:
        print(e)
        print(sys.exc_type) 

CodePudding user response:

Is your code failing with an error? I have this happening.I removed the extra function call def init().

import pandas_datareader.data as web
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import sys

plt.style.use('ggplot')
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(12, 5))

# set up investment choice and start/end dates
choice = str(input('Please enter your investment symbol: '))
start = str(input('Please enter your comparison starting date(mm/dd/yyyy):'))
end = dt.date.today()
symbol = '^GSPC', choice  # S&P500 symbol and your choice for comparison

# source of data and method of acqusition of data
source = 'yahoo'
data = web.DataReader(symbol, source, start, end)['Adj Close']

# adjust data shares for even start:
numer = data.iat[0, 0]
denom = data.iat[0, 1]  # call starting date value for chosen symbol
shares = numer / denom  # compute number of shares for even start

data[choice] = shares * (pd.DataFrame(data[choice]))  # Shares*share price

x1, y1, y2, y3 = [], [], [], []

def init():
        pass

def animate(i):
        if (len(data) - 1) == i:
           anim.event_source.stop()
        x1.append(data['^GSPC'].index[i])
        y1.append((data['^GSPC'].values[i]))
        y2.append((data[choice].values[i]))

        axes.plot(x1, y1, color="red")
        axes.plot(x1, y2, color="blue")


if __name__ == '__main__':
        try:
                anim = FuncAnimation(fig, animate, init_func=init, interval=1)
                # plt.plot(data)
                plt.xlabel('Days')
                plt.ylabel('Dollars')
                plt.title('The S&P500 (red) vs. Your Investment (blue),'
                          ' Using Adjusted Share Amounts for Even Start')
                # legend(['S&P500', choice])
                plt.show()

        except IndexError as e:
                print(e)
                print(sys.exc_type)

If you don't need animation, then the code below is without animation. Changed your code somewhat. Removed the obviously unnecessary creation of arrays: x1,y1,y2,y3.

import pandas_datareader.data as web
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt


plt.style.use('ggplot')
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(12, 5))

# set up investment choice and start/end dates
choice = str(input('Please enter your investment symbol: '))
start = str(input('Please enter your comparison starting date(mm/dd/yyyy):'))
end = dt.date.today()
symbol = '^GSPC', choice  # S&P500 symbol and your choice for comparison

# source of data and method of acqusition of data
source = 'yahoo'
data = web.DataReader(symbol, source, start, end)['Adj Close']

numer = data.iat[0, 0]
denom = data.iat[0, 1]  # call starting date value for chosen symbol
shares = numer / denom  # compute number of shares for even start

data[choice] = shares * (pd.DataFrame(data[choice]))  # Shares*share price

axes.plot(data['^GSPC'].index, data['^GSPC'], color="red")
axes.plot(data[choice].index, data[choice], color="blue")

plt.xlabel('Days')
plt.ylabel('Dollars')
plt.title('The S&P500 (red) vs. Your Investment (blue),' ' Using Adjusted Share Amounts for Even Start')
# legend(['S&P500', choice])
plt.show()
  • Related