【问题标题】:Pandas plot multiple category linesPandas 绘制多条类别线
【发布时间】:2018-03-24 20:22:19
【问题描述】:

假设我有以下数据...

date      Score  category                 
2017-01-01   50.0         1
2017-01-01  590.0         2
2017-01-02   30.0         1
2017-01-02  210.4         2
2017-01-03   11.0         1
2017-01-03   50.3         2

因此,我每天都有多个类别,每个类别都有一个分数。 到目前为止,这是我的代码...

vals = [{'date': '2017-01-01', 'category': 1, 'Score': 50},
         {'date': '2017-01-01', 'category': 2, 'Score': 590},
         {'date': '2017-01-02', 'category': 1, 'Score': 30},
         {'date': '2017-01-02', 'category': 2, 'Score': 210.4},
         {'date': '2017-01-03', 'category': 1, 'Score': 11},
         {'date': '2017-01-03', 'category': 2, 'Score': 50.3}]
df = pd.DataFrame(vals)
df.date = pd.to_datetime(df['date'], format='%Y-%m-%d')
df.set_index(['date'],inplace=True)

这导致了如下奇怪的情节。

我想要多行,每个类别一个,X 轴上的日期 - 我该怎么做?

【问题讨论】:

    标签: pandas matplotlib


    【解决方案1】:

    你可以使用 groupby 和 plot

    fig, ax = plt.subplots()
    for label, grp in df.groupby('category'):
        grp.plot(x = grp.index, y = 'Score',ax = ax, label = label)
    

    【讨论】:

      【解决方案2】:

      让我们尝试使用带有ax=ax 和参数secondary_y=True 的轴:

      ax = df.plot(x=df.index, y='Score')
      df.plot(x=df.index, y='category', secondary_y=True, ax=ax)
      

      输出:

      或者如果@Vaishali 情节是你想要的,你可以用这个单线来做。

      df.set_index('category',append=True).unstack()['Score'].plot()
      

      输出:

      【讨论】:

      • 你确实喜欢 set_index(),stack,unstack!:)
      • @Vaishali。谢谢!
      猜你喜欢
      • 2015-10-09
      • 2022-01-19
      • 2014-07-27
      • 2021-01-15
      • 2021-12-20
      • 1970-01-01
      • 2021-08-28
      • 2014-02-02
      相关资源
      最近更新 更多