Plotting time series with multicolor line in Python

Viewed 228

This my dataset:

import pandas as pd
from datetime import datetime
import numpy as np

date_rng = pd.date_range(start='2020-07-01', end='2020-07-20', freq='d')
df = pd.DataFrame(date_rng, columns=['date'])
df['data'] = np.random.randint(0,100,size=(len(date_rng))).cumsum()
df['Signal'] = [0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1] 

I would like to color the line according to the column "Signal", e.g. if Signal = 0 color the line blue, if Signal = 1, color the line orange.

I tried the following using seaborn, which is not what I want. I want to have one line with with 2 colors.

sns.lineplot(data=df, x="date", y="data", hue="Signal")

enter image description here

Any help would be much appreciated!

1 Answers
import pandas as pd
from datetime import datetime
import numpy as np

date_rng = pd.date_range(start='2020-07-01', end='2020-07-20', freq='d')
df = pd.DataFrame(date_rng, columns=['date'])
df['data'] = np.random.randint(0,100,size=(len(date_rng))).cumsum()
df['Signal'] = [0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1]

sig_0 = np.ma.masked_where(df['Signal'] ==0, df['data'])
sig_1 = np.ma.masked_where(df['Signal'] ==1, df['data'])
plt.plot(df['date'], sig_0, df['date'], sig_1)

This will give you following plot. enter image description here

The gaps correspond to the points where your signal values moves form 0 to 1 or 1 to 0. you can fill those gaps with some other color by putting an additional plot command

plt.plot(df['date'], df['data'], color='grey')
plt.plot(df['date'], sig_0, df['date'], sig_1)

Resulting Figure enter image description here

Related