根据条件颜色绘图显示图例

时间:2021-05-02 18:02:00

标签: python plotly-python

我有 2D 点,标记为 True/False。我想做一个散点图,这样 True 点会是绿色的, False 点会是红色的。另外,我希望侧面有一个图例显示{green_dot}=True,{red_dot}=False。我怎样才能添加这样的图例?

这是一个最小的例子。我必须使用 go.Scatter(),其他一切都可以更改。

import numpy as np
import plotly.graph_objects as go
x = np.arange(-3,3)
color = (x>=0).astype('int')
fig = go.Figure(go.Scatter(x=x, 
                           marker=dict(color=color,
                                      colorscale=[[0,'red'],[1,'green']]),                                
                                      showlegend=True))
fig.show()

enter image description here 可以看出,图例的信息量并不大。

1 个答案:

答案 0 :(得分:1)

您可以将数据拆分为带有 True 标记点的列表和带有 False 标记点的列表。

import numpy as np
import plotly.graph_objects as go

x = np.arange(0, 100)
y = np.random.randn(100)
color = np.random.randint(2, size=100)

fig = go.Figure()

trace1 = np.where(color==0)
trace2 = np.where(color==1)
fig.add_trace(go.Scatter(x=x[trace1],
                         y=y[trace1],
                         mode='markers',
                         name='false',
                         marker=dict(color='red')))
fig.add_trace(go.Scatter(x=x[trace2],
                         y=y[trace2],
                         mode='markers',
                         name='true',
                         marker=dict(color='green')
                         ))                         
fig.show()

enter image description here