Python Plotly: Coloring go.Scatter lines according to separate array value

Hi, I’m trying to plot multiple traces on one figure and color the lines according to a continuous color scale using plotly.graph_objects. I’m having trouble getting them to color correctly. Example below:


import plotly.graph_objects as go
import numpy as np

x = np.array([[0,1,2,3,4,5],
[0,1.1,2.1,3.1,4.1,5.1],
[1,2,3,4,5,6],
[2,3,4,5,6,7],
[2,3.1,4.1,5.1,6.1,7.1],
[3,4,5,6,7,8]])
vals = [0,0,1,2,2,3]
nums = [1,2,3,4,5]
fig = go.Figure()
for i, row in enumerate(x):
fig.add_trace(go.Scatter(x=nums, y=row, name=vals[i], mode='lines',
marker=dict(color=vals, cmax=3, cmin=0, colorscale='Viridis')))
fig.show()


I would like for the color of each trace to be determined by vals, so the first two traces would have the same color (purple on the Viridis scale?) since they have the same vals[i] value, the fourth and fifth traces would also have matching colors, and the sixth trace would be the max value of the color scale (yellow on the Viridis scale?)

Thanks!

HI @sean412 welcome to the forums.

If you change to mode='lines+markers you will see, that the markers are colored depending on their value. The thing is, that you want to color the lines which can be done via line=dict(color=your_discrete_color)
You can specify only one color per line.

If you want to use the viridis colorscale for the line colors, you’ll hav to convert it to a discrete values, here an example:

1 Like