Change color of continuous line based on value

Hi @yogi_dhiman ,

I think there is no built in function for this. There are two possible solutions I came up with, the first does not answer your question but could be a option, the second includes some preparation of your data first.

The first is coloring the markers instead of the line:

import plotly.graph_objects as go
import numpy as np

# generate data
x = np.arange(0, 8*np.pi, 0.1)
y = np.sin(x)

# cutoff value
cutoff = 0

# generate color list
colors=['red' if val < cutoff else 'blue' for val in y]

# create trace
trace = go.Scatter(
    x=x, 
    y=y, 
    mode='markers+lines', 
    marker={'color': colors}, 
    line={'color': 'gray'}
)

# crate figure, plot 
fig = go.Figure(data=trace)
fig.show()

result:

The second option adds each line segment between two points as a new trace. In proximity to the cutoff value the line color is not correct if one of the two y- values lies above the cutoff and the other y-value lies below the cutoff. If you prepare your data so that this does not occur (i.e serch for those cases and create a midpoint) the line color should be accurate.

import plotly.graph_objects as go
import itertools as it
import numpy as np

# generate data
x = np.arange(0, 8*np.pi, 0.1)
y = np.sin(x)

# cutoff value
cutoff = 0

# create coordinate  pairs
x_pairs = it.pairwise(x)
y_pairs = it.pairwise(y)

# generate color list
colors=['red' if any([i < cutoff for i in y_values]) else 'blue' for y_values in it.pairwise(y)]

# create base figure
fig = go.Figure()

# add traces (line segments)
for x, y, color in zip(x_pairs, y_pairs, colors):
    fig.add_trace(
        go.Scatter(
            x=x,
            y=y, 
            mode='lines', 
            line={'color': color}
        )
    )
    
fig.update_layout(showlegend=False)

result:

mrep linecolor

2 Likes