【问题标题】:plot chart with multi lines and group by column value绘制多行图表并按列值分组
【发布时间】: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


【解决方案1】:

你会考虑seaborn

import seaborn as sns

df = pd.read_csv('file.csv')
sns.lineplot(data=df, x='Date', y='value', hue='Case')

如果你不这样做,pandas 可以:

fig,ax = plt.subplots()
for k,v in df.groupby('Case'):
    v.plot(x='Date',y='value', ax=ax)

【讨论】:

  • 检查更新的问题。我发布了我的代码,但它还没有真正起作用
猜你喜欢
  • 1970-01-01
  • 2020-04-08
  • 2017-05-24
  • 2022-08-16
  • 2020-07-09
  • 1970-01-01
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多