Python plotly-向图例添加水平线

Python plotly-向图例添加水平线,python,plotly-python,Python,Plotly Python,我想在下面的图表中添加一条水平线,这样它也会出现在图例中 目标是通过单击图例,允许根据用户选择使线条出现\消失。 有什么想法吗 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_t

我想在下面的图表中添加一条水平线,这样它也会出现在图例中

目标是通过单击图例,允许根据用户选择使线条出现\消失。 有什么想法吗

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()

将所有记录道存储在列表中。然后将每个绘图添加到列表中

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()

如果您只想要一个图例,您可以快速向每个绘图添加虚线,并在一个绘图中将
showlegend
设置为False。如果希望一个图例条目控制两个子地块,则需要使用legendgroup参数。此处给出了R中的一个示例:。因此,不是一个完整的答案,而是一个可能有用的提示:)