简体   繁体   中英

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?

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()

If you use Plotly Express, you can pass the parameter color_discrete_map in px.scatter() . For example:

px.scatter(df, x='datetime', y='measurement', 
           color='target', 
           color_discrete_map={'value1': 'green', 'value2': 'red'})

Source: Manipulating legend in Scatter plot in python plotly package

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM