How to manually set the color of points in plotly express scatter plots
Asked Answered
N

3

36

https://plotly.com/python/line-and-scatter/ has many scatter plot examples, but not a single one showing you how to set all the points' colours within px.scatter:

# x and y given as DataFrame columns
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.show()

I've tried adding colour = 'red' etc doesn't work. These examples only show you how to colour by some other variable.

In principle I could add another feature and set it all the same but that seems a bizzare way of accomplishing the task....

Nonpartisan answered 14/8, 2020 at 13:41 Comment(0)
D
26

For that you may use the color_discrete_sequence argument.

fig = px.scatter(df, x="sepal_width", y="sepal_length", color_discrete_sequence=['red'])

This argument is to use a custom color paletter for discrete color factors, but if you are not using any factor for color it will use the first element for all the points in the plot.

More about discrete color palletes: https://plotly.com/python/discrete-color/

Dhruv answered 14/8, 2020 at 13:53 Comment(1)
How about for a go.Surface which only accepts surfacecolor?Ilyse
T
9

As far as I understand your question, I would try to answer it.

The parameter 'color' only accepts the column names.
In your case, you can consider using update_traces()

import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.update_traces(marker=dict(
        color='red'))
fig.show()

Reference: https://plotly.com/python/marker-style/

Tucson answered 14/8, 2020 at 13:55 Comment(1)
Thanks, but that same a truely insane system compared to other plotting packages (ggplot, matplotlib etc...)Nonpartisan
A
6

You do not have to add another feature to get what you want here. Thanks to Python's method chaining, you can just include .update_traces(marker=dict(color='red')) to manually assign any color of your choosing to all markers.

Plot:

enter image description here

Code:

# x and y given as DataFrame columns
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df,x="sepal_width",                         
                    y="sepal_length"
                 ).update_traces(marker=dict(color='red'))
fig.show()

Antitoxic answered 16/8, 2020 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.