Can we have square shape legends for scatter or line graphs?

Hi community,

By default the legend items shape is associated to the type of graph i.e square for bars, bubble for scatter and line for line charts.
image

image

I want to keep the legend shapes to be square for consistancy throughout my app irrespective of the chart type, is that possible?

Thank you!

HI @dataturnsmeon, i think that is not possible unfortunately. A time ago I investigated how to tweak the legend representation but I did not succeed.

IMHO this a weak point of plotly that you can not “fake” the legend, it is always related to the data. At least, I did not figure out how yet.

Hello @dataturnsmeon @AIMPED , I think that you can create your own function using annotations and fig.add_shape

@AbdelAnlah, I’m intrigued. How would you do that?

Hello @AIMPED. From my understanding this is what @dataturnsmeon want.
showlegend False and you have your fake legend.
Base on your work, you can automate it and put it where you want.

import plotly.express as px
color = { 'setosa':'lightsalmon','versicolor':'lightseagreen','virginica':'royalblue'}
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
                 size='petal_length', hover_data=['petal_width'],color_discrete_map=color)

#------------------------------------ fake legend -------------------------------------------------------
fig.add_shape(type="rect",
    xref="paper", yref="paper",
    x0=.46, y0=1.17,
    x1=.47, y1=1.12,
    line=dict(
        color="lightsalmon",
        # width=3,
    ),
    fillcolor="lightsalmon",
)

fig.add_shape(type="rect",
    xref="paper", yref="paper",
    x0=.56, y0=1.17,
    x1=.57, y1=1.12,
    line=dict(
        color="lightseagreen",
        # width=3,
    ),
    fillcolor="lightseagreen",
)

fig.add_shape(type="rect",
    xref="paper", yref="paper",
    x0=.67, y0=1.17,
    x1=.68, y1=1.12,
    line=dict(
        color="royalblue",
        # width=3,
    ),
    fillcolor="royalblue",
)

annotations = []
annotations.append(dict(xref='paper', yref='paper',
                        x=.5, y=1.2,
                        text='setosa',
                             font=dict(family='garamond', size=20,),
                        showarrow=False))

annotations.append(dict(xref='paper', yref='paper',
                        x=.615, y=1.2,
                        text='versicolor',
                             font=dict(family='garamond', size=20,),
                        showarrow=False))

annotations.append(dict(xref='paper', yref='paper',
                        x=.75, y=1.2,
                        text='virginica',
                             font=dict(family='garamond', size=20,),
                        showarrow=False))

fig.update_layout(annotations=annotations)
fig
1 Like

@AbdelAnlah, thanks for the explanation and the idea. While this could be a solution, I still would prefer to have a builtin option to “fake” the legend.

1 Like