简体   繁体   中英

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']])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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