6

I would like to add a horizontal line to the below charts so it will appear in the legend as well.

The goal is to allow to make the line appear\disappear per user choice by clicking on the legend. Any ideas?

import plotly.graph_objects as go

tips = px.data.tips()
fig = make_subplots(rows=2, cols=2, shared_xaxes=False, vertical_spacing=0.3,horizontal_spacing=0.05)

#Scatter plot
fig.append_trace(go.Scatter(
        x=tips['total_bill'],
        y=tips['tip'], 
        mode = 'markers',
        marker=dict( size=7),
        showlegend = True), 
        row=1, col=1)

#Box plot
fig.add_trace(go.Box(
            y=tips['tip'],
            x = tips['sex'],
            boxpoints='all',jitter=0.5,whiskerwidth=0.2,marker_size=5,line_width=2),
            row=1, col=2)

#Add horizontal lines
shapes = [
{'type': 'line','x0': 5,'y0': 5,
'x1': 50,'y1' : 5,'xref': 'x1', 
'yref': 'y1','line': {'color': 'red','width': 4, 'dash':'dashdot'}},

{'type': 'line','x0': 'Female','y0': 5,
'x1': 'Male','y1' : 5,'xref': 'x2', 
'yref': 'y2','line': {'color': 'red','width': 4, 'dash':'dashdot'}},
        ]

fig['layout'].update(shapes=shapes)

fig.show()

enter image description here

2
  • If you only want to have a legend you can quickly add dashed lines to each plot and set the showlegend to False in one plot. If you want to have it that one legend entry controls both subplots you need to use the legendgroup parametre. An example in R is given here: stackoverflow.com/a/46157158/11701819 . So not a full answer but a hint that might help :) Commented Sep 16, 2020 at 9:59
  • This question is similar to: Plotly add hline to existing legend entry from scatter plot. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 10, 2024 at 15:25

1 Answer 1

3

Store all your traces in a list. Then add each of your plots to the list.

fig = go.Figure()
data = []

data.append(go.Scatter(
        x=tips['total_bill'],
        y=tips['tip'], 
        mode = 'markers',
        marker=dict( size=7))

data.append(
    go.Scatter(
        x=(5,5),
        y=(50,5),
        mode='lines',
        name='trace 0',
        yaxis='y1'
    ))

layout = go.Layout(title='Some Title',showlegend=True)

fig = go.Figure(data=data, layout=layout)

fig.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.