Search code examples
pythonplotlyplotly-dash

Marker Color based on String Value Plotly Python


Pretty simple question here, but I cannot seem to figure it out. I have a dataframe column with 3 possible values:

print(df['Site'])

0        ABC
1        EFG
2        ABC
3        ABC
4        HIJ

When I plot, each site has the same color, but I would each marker to have a color to represent the site. I have tried to following 2 options with no luck:

fig.add_trace(go.Scatter(x=df['Reported Date'], y=df['Score'],
    mode='markers', 
    marker= dict(color=list(map(SetColor, df['Site']))),
    name='Points', 
    text="Site: " + df['Site'].map(str) + " " + "Ticket: "+ df['Ticket ID'].map(str)))
fig.add_trace(go.Scatter(x=df['Reported Date'], y=df['Score'],
    mode='markers', 
    marker_color= df['Site'],
    name='Points', 
    text="Site: " + df['Site'].map(str) + " " + "Ticket: "+ df['Ticket ID'].map(str)))

I know that Plotly/Dash wants an integer. Is there a work around for this? How can I plot site color in the markers?


Solution

  • I would start with a dictionary mapping colors and sites.

    d = {
        'ABC':'red',
        'DEF':'green',
        'GHI':'black'
    }
    

    You can use any HTML color name there.

    Then, you can make a list of colors based on your dict.

    colors = [d[k] for k in df['Site'].values]
    

    Finally, you can pass marker_color=colors to fig.add_trace()