简体   繁体   English

使用 Pandas 按组绘制线条

[英]plot line by group using Pandas

I am trying to plot values in a column and color them based on a group in a different column by manually passing colors from outside.我试图通过从外部手动传递颜色来绘制列中的值并根据不同列中的组为它们着色。 I assigned blue to test and red to train groups.我将蓝色分配给测试,红色分配给训练组。 But the following code is only plotting values in only blue color.但以下代码仅以蓝色绘制值。

import datetime
import pandas as pd

dft2 = pd.DataFrame({'A': [1,3,3,4,1,3,3,4],
                    'B': [2015, 2016, 2017,2018, 2019, 2020, 2021, 2022],
                    'C': pd.Categorical(["test", "train", "test", "train","train","train","train","train"])})

dft2 = dft2.set_index('B')
colors = {'test': 'b', 'train': 'r'}
dft2['A'].plot(figsize=(24,3),  rot=90, color=[colors[i] for i in dft2['C']])

You may want the scatter-plot version您可能需要散点图版本

import datetime
import pandas as pd


dft2 = pd.DataFrame({'A': [1,3,3,4],
                'B': [2015, 2016, 2017,2018],
                'C': pd.Series(1, index=list(range(4)), dtype='float32'),
                'D': np.array([3] * 4, dtype='int32'),
                'E': pd.Categorical(["test", "train", "test", "train"]),
                'F': 'foo'})

dft2.plot.scatter(x='B',y='A',c=['b' if i== 'test' else 'r'  for i in dft2['E']])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM