如何为Plotly Scatter散点图设置离散色条?
如何为Plotly Scatter散点图设置离散色条?
我最近遇到个Plotly的问题:我定义了5种颜色,用来给go.Scatter散点图里的标记点上色,但想要色条(图例)显示这些离散的颜色值时,结果色条却是空白的,就像图里那个标题为"outputs"的白色空条一样。
可复现的示例代码
import numpy as np import plotly.graph_objects as go #Data for testing outputs = np.random.choice([0, 1, 2, 3, 4], size=100) #Figure marker_palette=[ 'rgb(39, 100, 25)', # ++ 'rgb(156, 207, 100)', # + 'rgb(247, 247, 247)', # 0 'rgb(232, 150, 196)', # - 'rgb(142, 1, 82)', # -- ] scatter = go.Scatter( x=np.random.randn(100), y=np.random.randn(100), mode='markers', marker_color=[marker_palette[o] for o in outputs], marker=dict( # color=outputs, colorscale=marker_palette, #creates a continuous scale - not what I want colorbar={ 'title': 'outputs', 'tickmode': 'array', 'tickvals': np.unique(outputs), 'ticktext': ['++', '+', '0', '-', '--'] }, #/colorbar ), #/marker ) go.Figure(scatter)
我能轻松做出连续色条,但就是搞不定离散的那种。而且我更倾向于用graph_objects的解决方案,因为想看看内部具体是怎么配置的(不过这不是硬性要求)。
到底该怎么设置才能让色条显示出这些离散的颜色呢?
解决方案
问题出在你直接给每个标记点指定了具体颜色,但没有建立数值到颜色的映射关系,Plotly自然无法生成对应的离散色条。我们只需要调整一下配置,让Plotly基于outputs的数值来关联颜色,同时明确指定离散的颜色区间:
import numpy as np import plotly.graph_objects as go #Data for testing outputs = np.random.choice([0, 1, 2, 3, 4], size=100) #Figure marker_palette=[ 'rgb(39, 100, 25)', # ++ 'rgb(156, 207, 100)', # + 'rgb(247, 247, 247)', # 0 'rgb(232, 150, 196)', # - 'rgb(142, 1, 82)', # -- ] scatter = go.Scatter( x=np.random.randn(100), y=np.random.randn(100), mode='markers', marker=dict( color=outputs, # 绑定数值,让Plotly基于数值映射颜色 colorscale=marker_palette, # 使用自定义的离散颜色列表 cmin=-0.5, # 最小值边界,让每个数值对应颜色区间的中点 cmax=4.5, # 最大值边界,确保每个数值独占一个颜色区间 colorbar={ 'title': 'outputs', 'tickmode': 'array', 'tickvals': [0, 1, 2, 3, 4], 'ticktext': ['++', '+', '0', '-', '--'], 'tickwidth': 2, 'ticklen': 10 }, showscale=True # 确保色条显示出来 ) ) go.Figure(scatter).show()
关键说明
- 把
marker_color换成color=outputs:让Plotly知道要基于outputs的数值来分配颜色,而不是直接给每个点硬编码颜色; - 设置
cmin=-0.5和cmax=4.5:这两个值刚好把每个整数数值(0-4)框在独立的颜色区间里,避免颜色之间出现渐变; - 保留
colorscale=marker_palette:用你定义的5种颜色作为离散的颜色映射; - 确保
showscale=True:显式开启色条显示,之前的代码里可能漏掉了这一点。
这样调整后,色条就会清晰显示你定义的5种离散颜色,每个颜色对应对应的标签啦!
备注:内容来源于stack exchange,提问作者MuhammedYunus
相关产品推荐
相关产品推荐

