使用 Pandas 数据框以不同颜色绘制多条线 [英] Plotting multiple lines, in different colors, with pandas dataframe

查看:55
本文介绍了使用 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')

输出是这样的:

有没有办法让熊猫知道有两个集合?并相应地将它们分组.我希望能够将列 color 指定为设置微分器

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 有效地将数据转换为:

pivot effectively turns the data into:

这篇关于使用 Pandas 数据框以不同颜色绘制多条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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