Search code examples
pythondataframematplotlibplotmatplotlib-animation

how to make a multi-colored line in matplotlib


I am trying to make a multicolor line plot using matplotlib. The color would change given a specific value in a column of my datataframe

time v1 v2 state
0 3.5 8 0
1 3.8 8.5 0
2 4.2 9 1
3 5 12 0
4 8 10 2

My code for now, which just display the plot normally without the color:

cols=['v1','v2']
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(15, 15))
df.plot(x='time',y=cols,subplots=True, ax=axes)   
plt.legend()
plt.xticks(rotation=45)
plt.show()

The result would be something like that (2nd graph), with the line changing color given the column state (red,blue,green) with 3 distinct colors

result


Solution

  • for state, prev, cur in zip(df['state'].iloc[1:], df.index[:-1], df.index[1:]):
        if state==0: 
            color='blue'
        elif state==1:
            color='orange'
        else:
            color='green'
        plt.plot([df["time"][prev],df["time"][cur]],df.loc[[prev,cur],['v1','v2']], c=color)
    plt.xticks(rotation=45)
    plt.show()