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

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