使用pandas数据帧绘制多行

时间:2015-03-24 12:57:59

标签: python pandas plot

我的数据框如下所示

   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

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

当我执行以下操作时:

df.plot(x='x', y='y')

输出是这样的:

有没有办法让熊猫知道有两套?并相应地分组。我希望能够指定列的颜色'作为集合差异因素

4 个答案:

答案 0 :(得分:51)

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

for key, grp in df.groupby(['color']):

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()

的产率 enter image description here

答案 1 :(得分:19)

另一种简单的方法是使用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()

result

数据透视有效地将数据转换为:

enter image description here

答案 2 :(得分:4)

如果已安装pivot,则更简单的方法不需要您执行import seaborn as sns sns.lineplot(data=df, x='x', y='y', hue='color')

@empty

答案 3 :(得分:-3)

您可以使用此代码获取您的愿望输出

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df

  color  x   y
0   red  0   0
1   red  1   1
2   red  2   2
3  blue  3   9
4  blue  4  16
5  blue  5  25

绘制图表

a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)

plt.show()

<强>输出 The output result will look like this

相关问题