pandas 熊猫绘制多个类别线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46717359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:37:37  来源:igfitidea点击:

Pandas plot multiple category lines

pandasmatplotlib

提问by Craig

Say I have the following data...

假设我有以下数据...

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

So on a daily basis, I have multiple categories, each being assigned a score. Here's my code so far...

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

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)

Which results in a bizarre plot as below. enter image description here

这导致了一个奇怪的情节如下。 在此处输入图片说明

I'd like to have multiple lines, one for each category, and the date on the X-axis - how would I do this?

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

回答by Vaishali

You can use groupby and plot

您可以使用 groupby 和 plot

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

enter image description here

在此处输入图片说明

回答by Scott Boston

Let's try using axes with ax=axand parameter secondary_y=True:

让我们尝试使用带有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)

Output:

输出:

enter image description here

在此处输入图片说明

Or if @Vaishali plot is what you want you can do it with this one-liner.

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

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

Output:

输出:

enter image description here

在此处输入图片说明