如何在我的动画折线图中获取 x 轴上的日期?

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

我从网上借用了一些代码来制作这个折线图动画,但不幸的是它附带了一些用于 x 轴的 count() 而不是我从 Yahoo 导入的日期。我是新手,你能帮忙吗?

我得到了一个不错的情节,但我宁愿在 x 轴下显示日期。

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) 

您的代码是否因错误而失败?我已经 happening.I 删除了额外的函数调用 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)

如果你不需要动画,那么下面的代码是没有动画的。稍微更改了您的代码。删除了明显不必要的数组创建: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()