Setting color based on column in go.Scatter()

I have been following a tutorial and set up a scatterplot first with px.scatter:

df_iris = px.data.iris()
df_iris
fig = px.scatter(df_iris, x="sepal_width", y= "sepal_length", color="species",size="petal_length",hover_data=['petal_width'])
fig.update_layout(height=1000)

I then tried to do the same thing with go.Scatter() with this:

#Mere detaljeret plot

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df_iris.sepal_width,
    y=df_iris.sepal_length,
    mode='markers',
    marker_color=df_iris.species) )
            

fig.update_layout(height=1000)
fig

#marker_color=df_iris.species),

I get the error:
Invalid element(s) received for the ‘color’ property of scatter.marker

I have been reading through the documentation, but I don’t see a way to specify the color by a column with go.Scatter() similar to px.Scatter().
Is this possible?

hi @plottingly

see this go.Scatter example in the docs or the one below it.

Is that helpful?

Hi Adam

I have looked through that page and the more specific one for go.Scatter before asking here.

I still don’t see a way to do what I described in my question. There’s a manual way to specify the color of each trace added, but I don’t see how the trace can be split into multiple colors according to a specific column - like with the px function.

I see. What if you create a new column in your pandas dataframe that assigns integers to rows, based on species time. Then, you can use that numbered column in the color attribute, as such:

import plotly.express as px
import plotly.graph_objects as go

df_iris = px.data.iris()
df_iris['colors'] = df_iris['species'].apply(lambda x: 1 if x=='setosa' else (2 if x=='virginica' else 3))
print(df_iris.colors)

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df_iris.sepal_width,
    y=df_iris.sepal_length,
    mode='markers',
    marker=dict(color=df_iris.colors)
))

fig.update_layout(height=1000)
fig.show()

Would that work for you?

1 Like

Thanks for the suggestion Adam!
That does indeed work.

I was both trying to solve the specific case and to understand the logic of Plotly. This seems like an example where the px.scatter function has an advantage over the go.Scatter one - at least in terms of doing what I wanted shortly and cleanly. Good to know.

1 Like