【发布时间】:2020-11-12 18:51:06
【问题描述】:
我有一个来自 csv 文件的数据框,其中有 3 列“日期”、“值”和“案例”。我希望能够将数据绘制为折线图,其中有不同的案例,每个案例都应该有自己的线like this。所以这些案例很多,我在想必须有一些功能来“分组”这些案例并用不同的颜色将它们显示在不同的行中。我希望在我的图表中将日期作为 x 轴,将值作为 y 轴。我怎样才能做到这一点?
这是我的代码:(我是初学者,所以我的代码可能看起来很糟糕)
import pandas as pd
import matplotlib.pyplot as plt
def read_csvfile():
df = pd.read_csv('ebola_data_db_format.csv', sep= ',')
#remove the unneeded columns
df = df[df['Country'] != "Guinea 2"]
df = df[df['Country'] != "Liberia 2"]
#reset the index
df.reset_index(drop=True, inplace=True)
#group by country, now for every element v have a different country
for k, v in df.groupby('Country'):
#here I try to group by case and plot but it does not work
fig,ax = v.subplots()
for a,b in df.groupby('Case'):
b.plot(x='Date',y='value', ax=ax)
#v.to_csv(f'{k}.csv')
read_csvfile()
【问题讨论】:
-
fig,ax = v.subplots()应该是fig,ax = plt.subplots()。对于内部循环,使用for a,b in v.groupby('Case')。
标签: python pandas dataframe plot charts