Matplotlib动画图表无动效问题排查(Pandas数据异常)
Matplotlib动画图表无动效问题
我正在试验Matplotlib动画图表,使用公开CSV数据集时遇到图表无动效的问题。已更新教程中的数据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") # 旋转x轴标签 plt.subplots_adjust(bottom=0.2, top=0.9) # 调整布局让日期标签完整显示 plt.ylabel('死亡人数') plt.xlabel('日期') def buildmebarchart(i=int): plt.legend(df1.columns) p = plt.plot(df1[:i].index, df1[:i].values) # 仅取到第i行的数据集 for i in range(0, 4): p[i].set_color(color[i]) # 设置每条曲线的颜色 animator = ani.FuncAnimation(fig, buildmebarchart, interval=50) plt.show()
运行结果
运行后显示一张无数据的静态图表,仅包含坐标轴标签和空白绘图区域。
问题更新
通过断点调试发现,问题疑似出在这行代码:
p = plt.plot(df1[:i].index, df1[:i].values)
打印结果显示df1[:i].index和df1[:i].values均为空。
内容的提问来源于stack exchange,提问作者Michael Hawkins
相关产品推荐
相关产品推荐

