- you need a trace for each color segment
- Plotly Express approach is simple to use for this
import numpy as np
import plotly.express as px
x = np.linspace(-1, 1, 101)
y = x**2
# Slope in-between of the knots
dy = (x[1:] + x[:-1])
# all arrays need to be same length
fig = px.line(x=x, y=y, color=np.pad(dy, (1,0), mode="edge")>0)
fig.update_layout(showlegend=False)

no gaps - generate multi-trace figure using list for y
px.line(x=x, y=[y, np.where(np.pad(dy, (1,0), mode="edge")>0,y,np.nan)]).update_layout(showlegend=False)
multiple segments (25) no gaps
Per comments, you are looking for multiple segments (not just 2). This is really discrete bins pd.cut()
, plus filling gaps pandas ffill()
df = pd.DataFrame({"x":x,"y":y,"dy":np.pad(dy, (1,0), mode="edge")})
df["color"] = pd.cut(df["dy"], bins=25, labels=False)
df = df.set_index(["x","color"]).drop(columns=["dy"]).unstack("color").droplevel(0,1)
px.line(df.ffill(limit=1, axis=1), x=df.index, y=df.columns)
