Automatically Pick Colors When Using `add_trace`

I’m using the plotly.graph_objects interface, and trying to add data with add_trace that automatically picks colors for a categorical variable. Here’s an example:

data= pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv")

fig = go.Figure().add_trace(go.Scatter(x=data['Postal'],
                                y=data['Population'],
                                mode='markers',
                                marker_color=data['Postal'],
                                text=data['State'])) 

This fails, saying marker_color has to be a real array of colors, as opposed to an array of random strings to which colors will be assigned. Plotly express handles lists of strings by assigning colors to each distinct string. Is there a way for me to emulate that behavior with graph_objects? Or a helper function to convert list of arbitrary strings to list of colors?

data= pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv")

#create dict with unique color values
color_dict={}
x=0
for postal in data['Postal']:
    if postal not in color_dict:
        color_dict[postal]=x
        x += 1
        
#create color list
color_list=[]
for postal in data['Postal']:
    color_list.append(color_dict[postal])


fig = go.Figure().add_trace(go.Scatter(x=data['Postal'],
                                y=data['Population'],
                                mode='markers',
                                marker_color=color_list,
                                marker_colorscale="Rainbow",
                                text=data['State'])) 

fig.show()
1 Like

Thanks for answering! I agree it’s definitely possible to just hand make the color_dict. Partially the reason I asked this is I don’t want to pick the colors myself, I just want to use whatever default color set plotly would have normally picked for ploty.express. Is there a way to do that?

I would guess px.express does it similarly in the background, but I have no idea which standard color scale is used for string values in px.express.

Here is the documentation about quantitative colors: