How to add categorical color legend for scatter plot created by graph_objects

E.g. for the following scatter plot example show in the offical document, how to add a categorical, rather than continuous, color legend for the four circles with different x values?

Do I have to add each circle using a trace to get the categorical, or discreet, color legend?

import plotly.graph_objects as go

fig = go.Figure(data=go.Scatter(
    x=[1, 2, 3, 4],
    y=[10, 11, 12, 13],
    mode='markers',
    marker=dict(size=[40, 60, 80, 100],
                color=[0, 1, 2, 3])
))

fig.show()

simplest would be to switch to plotly express: Bubble Charts .

Otherwise you are correct, you would need to add each trace seperately with a name:

Does this work for you?

import plotly.graph_objects as go

fig = go.Figure(data=go.Scatter(
    x=[1, 2, 3, 4],
    y=[10, 11, 12, 13],
    mode='markers',
    marker=dict(size=[40, 60, 80, 100],
                color=[0, 1, 2, 3])
))

fig.update_xaxes(tickmode = 'array',
                 tickvals = [1, 2, 3, 4],
                 ticktext = ['Elephant','Lion', 'Tiger', 'Dolphin'],
                 ticks="",
                 tickfont=dict(size=20)
                )

fig.show()

Edit: Sorry, misread, I guess. Color legend/trace will stay the same. Would like to know that too?!

Here is how you can do it:

  1. Plotly express:
import plotly.express as px
import panda as pd

df = pd.DataFrame({"x": ['Elephant','Lion', 'Tiger', 'Dolphin'], "y": [10, 11, 12, 13], "size": [40, 60, 80, 100]})

fig = px.scatter(
    df,
    x="x",
    y="y",
    color="x",
    size="size"
)

fig.update_xaxes(tickfont=dict(size=20))

or:

import plotly.graph_objects as go

fig = go.Figure()
for x, y, size in zip(['Elephant','Lion', 'Tiger', 'Dolphin'], [10, 11, 12, 13], [40, 60, 80, 100]):
    fig.add_trace(
            go.Scatter(
            x=[x],
            y=[y],
            name=x,
            mode='markers',
            marker=dict(size=size)
        )
    )

fig.update_xaxes(tickfont=dict(size=20))

1 Like

Great, thanks a lot!

Do you know why fig.update_layout(legend_itemsizing ='trace') does not work as expected?

import plotly.graph_objects as go

fig = go.Figure()
for x, y, size in zip(['Elephant','Lion', 'Tiger', 'Dolphin'], [10, 11, 12, 13], [40, 60, 80, 100]):
    fig.add_trace(
            go.Scatter(
            x=[x],
            y=[y],
            name=x,
            mode='markers',
            marker=dict(size=size)
        )
    )

fig.update_xaxes(tickfont=dict(size=20))

fig.update_layout(legend_itemsizing ='trace')

fig.show()