簡體   English   中英

使用 Pandas 按組繪制線條

[英]plot line by group using Pandas

我試圖通過從外部手動傳遞顏色來繪制列中的值並根據不同列中的組為它們着色。 我將藍色分配給測試,紅色分配給訓練組。 但以下代碼僅以藍色繪制值。

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

您可能需要散點圖版本

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