Change colour of curve according to its y-value in matplotlib

Hello, there is the possibility to color the y-values according to their value in matplotlib like

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm


x = np.linspace(0, 2*np.pi, 1000)
y = np.sin(2*x)
plt.scatter(x,y, c=cm.hot(np.abs(y)), edgecolor='none')
plt.show()

What is the corresponding way to do it in plotly?

import plotly.graph_objects as go
import numpy as np

N = 1000
t = np.linspace(0,10,100)
y = np.sin(t)

fig = go.Figure(
        data = [go.Scatter(x=t,y=y,mode = "lines")]
)
fig.show()

@ud.schn
You can plot lines colored according to y-values, but not with scatter mode="lines", but "markers", and with a sufficiently high density of points. (the density is also influenced by layout width and height)

import plotly.graph_objects as go
import numpy as np

N = 700
t = np.linspace(0,2*np.pi,N) #N sufficiently big to ensure high marker density
y = np.sin(t)

fig = go.Figure(go.Scatter(x=t,y=y,mode = "markers", marker=dict(color=y, size=3,  
                           colorscale="matter_r", colorbar_thickness=25)))
fig.update_layout(width=600, height=400)
fig.show()

line_y_color

1 Like

Iโ€™ve tried your script and indeed it worksโ€ฆ then I try to apply it to a script of mine that plots a 3D surface by Delaunay triangulation (since my data are irregularly scattered): when trying to display projection curves (of the 3D surface) onto the vertical planes (that is, XZ and YZ) coloring them according to the z value (of heatmap-type, that is cmap=plt.cm.jet), I get curves whose color is not proportional to the z value. Iโ€™ve tried

fig = go.Figure(go.Scatter(x=t,y=y,mode = โ€œmarkersโ€, marker=dict(color=y, size=3,
colorscale=โ€œmatter_rโ€, colorbar_thickness=25)))
fig.update_layout(width=600, height=400)
cset = ax.tricontour(x, y, z, c=cm.hot(np.abs(z)), zdir=โ€˜xโ€™, offset= 0, levels=np.linspace(0,6.7,32),cmap=plt.cm.jet)
cset = ax.tricontour(x, y, z, c=cm.hot(np.abs(z)), zdir=โ€˜yโ€™, offset=88, levels=np.linspace(12,88,32), cmap=plt.cm.jet)

Iโ€™ve also omitted the cmap=ply.cm.jet but that only changes the colors to a scale of greens.