我目前正在试验Matplotlib动画图表.有一个问题,在使用公共数据集时,数据不是动态的.我正在从一个公共CSV文件中提取数据,遵循来自this post的一些指导(它必须针对数据的URL之类的东西进行一些更新).我已经测试了我的Matplotlib安装,它以各种格式显示静态测试数据,没有问题.我不确定这是Pandas 在传递数据方面的问题,还是我在动画中错过了什么.
代码:
import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'
df = pd.read_csv(url, delimiter=',', header='infer')
df_interest = df.loc[
df['Country/Region'].isin(['United Kingdom', 'US', 'Italy', 'Germany'])
& df['Province/State'].isna()]
df_interest.rename(
index=lambda x: df_interest.at[x, 'Country/Region'], inplace=True)
df1 = df_interest.transpose()
df1 = df1.drop(['Province/State', 'Country/Region', 'Lat', 'Long'])
df1 = df1.loc[(df1 != 0).any(1)]
df1.index = pd.to_datetime(df1.index)
print(df1)
color = ['red', 'green', 'blue', 'orange']
fig = plt.figure()
plt.xticks(rotation=45, ha="right", rotation_mode="anchor") # rotate the x-axis values
plt.subplots_adjust(bottom=0.2, top=0.9) # ensuring the dates (on the x-axis) fit in the screen
plt.ylabel('No of Deaths')
plt.xlabel('Dates')
def buildmebarchart(i=int):
plt.legend(df1.columns)
p = plt.plot(df1[:i].index, df1[:i].values) # note it only returns the dataset, up to the point i
for i in range(0, 4):
p[i].set_color(color[i]) # set the colour of each curve
animator = ani.FuncAnimation(fig, buildmebarchart, interval=50)
plt.show()
Result (a static graph with no data):
UPDATE:个
似乎是这行Pandas 代码可能是罪魁祸首:
p = plt.plot(df1[:i].index, df1[:i].values)
当我插入断点以打印df1[:i].index和.value时,它们是空的.