我有一个来自csv文件的数据帧,其中我有3列"Date“、"value”和"Case“。我希望能够将数据绘制为折线图,其中有不同的情况,并且每个情况都应该有自己的线条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()发布于 2020-11-13 02:54:32
你会考虑seaborn吗?
import seaborn as sns
df = pd.read_csv('file.csv')
sns.lineplot(data=df, x='Date', y='value', hue='Case')如果你不愿意,熊猫可以这样做:
fig,ax = plt.subplots()
for k,v in df.groupby('Case'):
v.plot(x='Date',y='value', ax=ax)https://stackoverflow.com/questions/64809988
复制相似问题