Add two legends for two dimensions in plotly, i.e. one legend for the color, one for the symbol in plotly

gene_x 0 like s 225 view s

Tags:

import plotly.graph_objects as go
import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'category_1': ['A', 'B', 'A', 'B', 'A', 'B'],
                   'category_2': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
                   'value_1': [1, 2, 3, 4, 5, 6],
                   'value_2': [7, 8, 9, 10, 11, 12]})

fig = go.Figure()

# Create scatter plot for category_1
for cat in df['category_1'].unique():
    fig.add_trace(go.Scatter(x=df.loc[df['category_1'] == cat, 'value_1'],
                             y=df.loc[df['category_1'] == cat, 'value_2'],
                             mode='markers',
                             name=cat,
                             legendgroup='category_1',
                             marker=dict(symbol='circle')))

# Create scatter plot for category_2
symbols = {'X': 'star', 'Y': 'diamond'}
for cat in df['category_2'].unique():
    fig.add_trace(go.Scatter(x=df.loc[df['category_2'] == cat, 'value_1'],
                             y=df.loc[df['category_2'] == cat, 'value_2'],
                             mode='markers',
                             name=cat,
                             legendgroup='category_2',
                             marker=dict(symbol=symbols[cat], color='black'),
                             showlegend=True,
                             visible='legendonly'))

# Update legend properties
fig.update_layout(legend=dict(tracegroupgap=30))

# Add custom legend group names using annotations
fig.update_layout(
    annotations=[
        go.layout.Annotation(
            text="Group 1",
            x=1.05,
            y=1,
            xref="paper",
            yref="paper",
            showarrow=False,
            font=dict(size=14, color='black'),
            bgcolor='rgba(255, 255, 255, 0.8)',
            bordercolor='black',
            borderwidth=1,
            xanchor='left',
            yanchor='top',
            valign='top'
        ),
        go.layout.Annotation(
            text="Group 2",
            x=1.05,
            y=0.65,
            xref="paper",
            yref="paper",
            showarrow=False,
            font=dict(size=14, color='black'),
            bgcolor='rgba(255, 255, 255, 0.8)',
            bordercolor='black',
            borderwidth=1,
            xanchor='left',
            yanchor='top',
            valign='top'
        )
    ]
)

fig.show()

like unlike

点赞本文的读者

还没有人对此文章表态


本文有评论

没有评论

看文章,发评论,不要沉默


© 2023 XGenes.com Impressum