我目前正在试验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): enter image description here

UPDATE:

似乎是这行Pandas 代码可能是罪魁祸首:

p = plt.plot(df1[:i].index, df1[:i].values)

当我插入断点以打印df1[:i].index和.value时,它们是空的.

推荐答案

实际上,您的代码没有问题.我可以成功地将其作为脚本运行,而无需进行任何更改.以下是我的环境:

python                    3.8.5
pandas                    1.1.3
matplotlib                3.3.2

但我怀疑,你在Jupyter-Notebook工作.在这种情况下,您必须做出一些更改.首先,将matplotlib设置为在笔记本中交互工作.您可以使用以太notebooknbAgg作为后端(有关详细信息,请参阅The builtin backends):

%matplotlib notebook

接下来,停用最后一行代码:

#plt.show() <- comment or delete this line

应该行得通.考虑到我使用的是Jupyter-Notebook版本6.1.4.如果问题仍然存在,请更新说明以反映您的环境.


附注:try 使用ipympl作为备用后端.

Python相关问答推荐

使用pandas MultiIndex进行不连续 Select

在两极中实施频率编码

收件箱转换错误- polars.exceptions. ComputeHelp- pandera(0.19.0b3)带有polars

在Pandas框架中截短至固定数量的列

多处理代码在while循环中不工作

我必须将Sigmoid函数与r2值的两种类型的数据集(每种6个数据集)进行匹配,然后绘制匹配函数的求导.我会犯错

试图找到Python方法来部分填充numpy数组

如何让Flask 中的请求标签发挥作用

用合并列替换现有列并重命名

基于字符串匹配条件合并两个帧

如何获得每个组的时间戳差异?

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

如何创建一个缓冲区周围的一行与manim?

SQLAlchemy Like ALL ORM analog

所有列的滚动标准差,忽略NaN

根据列值添加时区

用渐近模计算含符号的矩阵乘法

如何在Pyplot表中舍入值

合并与拼接并举

Pandas:填充行并删除重复项,但保留不同的值