How to connect scatter points from different traces?

Hello :slight_smile:

I am trying to replicate the below plot using plotly.
image

I have plotted the data points as separate traces using go.Scatter but I am not sure how I can show the line connecting the three points as shown in above image. Check out my below code.

high = [5,3,8,6]
mid = [3.5,2,5.5,4]
low = [2,1,3,2]

x=[10,20,30,40]

fig = go.Figure()

fig.add_trace(go.Scatter(x=x, y=high, mode='markers', name='High', marker_color='#c92a52', marker_symbol='triangle-down', marker_size=15))
fig.add_trace(go.Scatter(x=x, y=mid, mode='markers', name='Mid', marker_color='black', marker_symbol='x-thin', marker_line_width=3))
fig.add_trace(go.Scatter(x=x, y=low, mode='markers', name='Low', marker_color='#4d70c9', marker_symbol='triangle-up', marker_size=15))

fig.update_layout(template='presentation')

fig.show()

Output:

How can I show the line connecting the three markers (High, Mid, Low) ? Thanks in advance !

Hi,

It is not possible to connect points in different traces to my knowledge.

There are at least two alternatives: adding the vertical segments as an extra Scatter trace or as a shape. They are both covered in the examples here.

I would go with the first approach, by modifying the 2nd example in the link I just mentioned to make vertical lines instead of a triangle and a rectangle.

Hope that this helps!

1 Like

Thanks @jlfsjunior, I’ll try out these suggestions :slight_smile:

Hi @dataturnsmeon,

Interesting question!

There is a workaround or hack :factory_worker: to add those individual lines between separate traces.
Those lines are nothing but very thin bars with individual bases.

Just add a bar trace in your existing code with the base set to the values in your low list and y will be difference between high and low as it represents the bar height. You can set the bar width to be more thinner than shown in the example below by setting a lower value.

high = [5,3,8,6]
mid = [3.5,2,5.5,4]
low = [2,1,3,2]

x=[10,20,30,40]

#calculating difference between high and low for setting bar height
diff = [h - l for h, l in zip(high, low)]

fig = go.Figure()

fig.add_trace(go.Scatter(x=x, y=high, mode='markers', name='High', marker_color='#c92a52', marker_symbol='triangle-down', marker_size=15))
fig.add_trace(go.Scatter(x=x, y=mid, mode='markers', name='Mid', marker_color='black', marker_symbol='x-thin', marker_line_width=3))
fig.add_trace(go.Scatter(x=x, y=low, mode='markers', name='Low', marker_color='#4d70c9', marker_symbol='triangle-up', marker_size=15))

# adding bar trace with base starting from values in low list, also setting the bar width very low
fig.add_trace(go.Bar(x=x, y=diff, base=low, width=0.01, marker_color='black', showlegend=False))

fig.update_layout(template='presentation')

fig.show()

3 Likes

Wow, just AMAZING @atharvakatre!

This works perfectly for my use-case.

Thanks for the help :pinched_fingers:

1 Like