用pandas数据框绘制多行 [英] Plotting multiple lines with pandas dataframe

查看:73
本文介绍了用pandas数据框绘制多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe that looks like the following

   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

I ultimately want two lines, one blue, one red. The red line should essentially be y=x and the blue line should be y=x^2

当我执行以下操作时:

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

输出是这样的:

有没有办法让大熊猫知道有两套?并将它们相应地分组.我希望能够将颜色"列指定为集合区分符

Is there a way to make pandas know that there are two sets? And group them accordingly. I'd like to be able to specify the column 'color' as the set differentiator

推荐答案

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

Another simple way is to use the pivot function to format the data as you need first.

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

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

pivot effectively turns the data into:

这篇关于用pandas数据框绘制多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆