pandas plot timeseries color per id of the individual time series

Viewed 381

I currently obtain the following plot:

enter image description here

But instead of plotting 2 separate time series which are not related, I want to plot the column metrik_0 with a different color per device_id.

import pandas as pd
from pandas import Timestamp
d = pd.DataFrame({'metrik_0': {Timestamp('2020-01-01 00:00:00'): -0.5161200349325471,
  Timestamp('2020-01-01 01:00:00'): 0.6404118012330947,
  Timestamp('2020-01-01 02:00:00'): -1.0127867504877557,
  Timestamp('2020-01-01 03:00:00'): 0.25828987625529976,
  Timestamp('2020-01-01 04:00:00'): -2.486778084008076,
  Timestamp('2020-01-01 05:00:00'): -0.30695039872663826,
  Timestamp('2020-01-01 06:00:00'): -0.6570670310316116,
  Timestamp('2020-01-01 07:00:00'): 0.3274964731894147,
  Timestamp('2020-01-01 08:00:00'): -0.8624113311084097,
  Timestamp('2020-01-01 09:00:00'): 1.0832911260447902},
 'device_id': {Timestamp('2020-01-01 00:00:00'): 9,
  Timestamp('2020-01-01 01:00:00'): 1,
  Timestamp('2020-01-01 02:00:00'): 1,
  Timestamp('2020-01-01 03:00:00'): 9,
  Timestamp('2020-01-01 04:00:00'): 9,
  Timestamp('2020-01-01 05:00:00'): 9,
  Timestamp('2020-01-01 06:00:00'): 9,
  Timestamp('2020-01-01 07:00:00'): 1,
  Timestamp('2020-01-01 08:00:00'): 1,
  Timestamp('2020-01-01 09:00:00'): 9}})

d.plot()

The following would work when using seaborn.

import seaborn as sns; sns.set()
d['device_id'] = d['device_id'].astype(str)
#display(d.head())
sns.lineplot(x='index', y='metrik_0', style='device_id', hue='device_id', data=d)

Can this be natively included in the call to plot from pandas?

1 Answers

Natively pandas can't do this natively. But you can go through a groupby():

fig, ax = plt.subplots()
for dev, df in d.groupby('device_id'):
    df.plot(y='metrik_0', ax=ax, label=dev)

Output:

enter image description here

Related