3

I have following dataset:

import pandas as pd
import matplotlib.pyplot as plt
dict = {'time':["2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05", "2017-01-06"],'val':[3.2, 10.2, 11.3, 4.9, 2.3], 
        'class': [0, 1, 1, 0,0]} 
df = pd.DataFrame(dict) 
df
    time         val    class
0   2017-01-02   3.2    0
1   2017-01-03   10.2   1
2   2017-01-04   11.3   1
3   2017-01-05   4.9    0
4   2017-01-06   2.3    0

I want to plot line for column "val", keeping x axis as 'df.time', meanwhile changing color of line based on 'class' column(when it is zero then for example blue line, when it is 1 then it changes color to red). my plot is as following

enter image description here

but desired is something like this:

enter image description here

Thanks!

Sascha
  • 687
  • 1
  • 8
  • 22

1 Answers1

2

Like in this question, you will just need to plot a bunch of lines:

# recommend
df['time'] = pd.to_datetime(df['time'])

plt.figure(figsize=(10,6))
for i in range(1,len(df)):
    s = df.iloc[i-1:i+1]
    color = 'r' if s['class'].eq(1).all() else 'C0'

    plt.plot(s['time'], s['val'], c=color)

plt.show()

Output:

enter image description here

For when you have a lot of rows, it might be better to use scatter:

plt.scatter(df['time'], df['val'], 
            color=np.where(df['class'], 'r','C0')
           )

Output (will look better with 10k rows):

enter image description here

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74