使用pandas数据帧绘制多行

sed*_*idw 44 python plot pandas

我有一个如下所示的数据框

   color  x   y
0    red  0   0
1    red  1   1
2    red  2   2
3    red  3   3
4    red  4   4
5    red  5   5
6    red  6   6
7    red  7   7
8    red  8   8
9    red  9   9
10  blue  0   0
11  blue  1   1
12  blue  2   4
13  blue  3   9
14  blue  4  16
15  blue  5  25
16  blue  6  36
17  blue  7  49
18  blue  8  64
19  blue  9  81
Run Code Online (Sandbox Code Playgroud)

我最终想要两条线,一条蓝色,一条红色.红线基本上应为y = x,蓝线应为y = x ^ 2

当我执行以下操作时:

df.plot(x='x', y='y')
Run Code Online (Sandbox Code Playgroud)

输出是这样的:

有没有办法让熊猫知道有两套?并相应地分组.我希望能够将列'color'指定为设置区分器

unu*_*tbu 60

您可以groupby根据颜色将DataFrame拆分为子组:

for key, grp in df.groupby(['color']):
Run Code Online (Sandbox Code Playgroud)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()

for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)

plt.legend(loc='best')
plt.show()
Run Code Online (Sandbox Code Playgroud)

产量 在此输入图像描述

  • 无法使解决方案起作用,因为我的数据集不是颜色,而参数“c”恰好是绘图线颜色。在 OP 的情况下,这很好,但对其他人来说会失败。如果您删除该参数,这个出色的解决方案也适用于所有其他数据集。 (2认同)

MrE*_*MrE 36

另一种简单的方法是使用该pivot函数首先根据需要格式化数据.

df.plot() 做其余的事

df = pd.DataFrame([
    ['red', 0, 0],
    ['red', 1, 1],
    ['red', 2, 2],
    ['red', 3, 3],
    ['red', 4, 4],
    ['red', 5, 5],
    ['red', 6, 6],
    ['red', 7, 7],
    ['red', 8, 8],
    ['red', 9, 9],
    ['blue', 0, 0],
    ['blue', 1, 1],
    ['blue', 2, 4],
    ['blue', 3, 9],
    ['blue', 4, 16],
    ['blue', 5, 25],
    ['blue', 6, 36],
    ['blue', 7, 49],
    ['blue', 8, 64],
    ['blue', 9, 81],
], columns=['color', 'x', 'y'])

df = df.pivot(index='x', columns='color', values='y')

df.plot()
Run Code Online (Sandbox Code Playgroud)

结果

pivot有效地将数据转换为:

在此输入图像描述

  • 这更优雅 (3认同)

Che*_*eng 7

如果已seaborn安装,则不需要您执行pivot以下更简单的方法:

import seaborn as sns

sns.lineplot(data=df, x='x', y='y', hue='color')
Run Code Online (Sandbox Code Playgroud)