简体   繁体   English

基于字符串值的标记颜色 Plotly Python

[英]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:我有一个包含 3 个可能值的 dataframe 列:

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.当我 plot 时,每个站点都有相同的颜色,但我会为每个标记都用一种颜色来代表该站点。 I have tried to following 2 options with no luck:我尝试过以下 2 个选项,但没有成功:

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?我知道 Plotly/Dash 想要一个 integer。有解决办法吗? How can I plot site color in the markers?我怎样才能在 plot 站点颜色中标记?

I would start with a dictionary mapping colors and sites.我将从映射 colors 和站点的字典开始。

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

You can use any HTML color name there.您可以在那里使用任何HTML 颜色名称

Then, you can make a list of colors based on your dict.然后,您可以根据您的 dict 列出 colors 列表。

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

Finally, you can pass marker_color=colors to fig.add_trace()最后,您可以将marker_color=colors传递给fig.add_trace()

If you use Plotly Express, you can pass the parameter color_discrete_map in px.scatter() .如果使用 Plotly Express,可以在px.scatter()中传入参数color_discrete_map 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资料来源: 在Scatter plot中操纵图例 python plotly package

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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