如何在Plotly.graph_objects中指定散点标记的离散颜色?
解决Plotly Graph Objects散点图离散标记颜色映射问题
color_discrete_sequence是Plotly Express的专属参数,plotly.graph_objects(go)的Scatter对象并不支持这个参数,所以你之前的写法无效。以下两种方法可以实现你需要的离散颜色映射需求:
方法1:提前将标签映射为颜色字符串
直接通过字典把label列的数值映射成对应的颜色字符串,再传给marker_color参数:
from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd # 模拟你的make3ClassLabel函数 def make3ClassLabel(target): return target % 3 # 构造模拟数据 df = pd.DataFrame({'target': range(100)}) fts = pd.DataFrame({ 'feat_x': range(100), 'feat_y0': [i*0.5 for i in range(100)], 'feat_y1': [i*0.8 for i in range(100)] }) fts['label'] = make3ClassLabel(df['target']) # 定义标签-颜色映射字典 color_map = {0: 'blue', 1: 'yellow', 2: 'red'} # 生成颜色列 fts['point_color'] = fts['label'].map(color_map) fig = make_subplots(rows=1, cols=2, shared_yaxes=True) # 第一个子图 fig.add_trace(go.Scatter( x=fts['feat_x'], y=fts['feat_y0'], mode='markers', marker_color=fts['point_color'] ), row=1, col=1) # 第二个子图 fig.add_trace(go.Scatter( x=fts['feat_x'], y=fts['feat_y1'], mode='markers', marker_color=fts['point_color'] ), row=1, col=2) fig.update_traces(marker=dict(size=1, line=dict(width=0))) fig.show()
方法2:使用自定义颜色刻度映射数值
通过marker的colorscale参数自定义数值到颜色的映射,配合cmin和cmax确保每个标签对应正确的颜色:
from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd # 模拟你的make3ClassLabel函数 def make3ClassLabel(target): return target % 3 # 构造模拟数据 df = pd.DataFrame({'target': range(100)}) fts = pd.DataFrame({ 'feat_x': range(100), 'feat_y0': [i*0.5 for i in range(100)], 'feat_y1': [i*0.8 for i in range(100)] }) fts['label'] = make3ClassLabel(df['target']) fig = make_subplots(rows=1, cols=2, shared_yaxes=True) # 第一个子图 fig.add_trace(go.Scatter( x=fts['feat_x'], y=fts['feat_y0'], mode='markers', marker=dict( color=fts['label'], # 自定义颜色刻度:0→blue,1→yellow,2→red colorscale=[[0, 'blue'], [1/2, 'yellow'], [1, 'red']], # 设置颜色范围边界,确保每个标签对应唯一颜色区间 cmin=-0.5, cmax=2.5, # 不需要颜色条可设为False,需要的话可以添加colorbar参数调整刻度 showscale=False ) ), row=1, col=1) # 第二个子图 fig.add_trace(go.Scatter( x=fts['feat_x'], y=fts['feat_y1'], mode='markers', marker=dict( color=fts['label'], colorscale=[[0, 'blue'], [1/2, 'yellow'], [1, 'red']], cmin=-0.5, cmax=2.5, showscale=False ) ), row=1, col=2) fig.update_traces(marker=dict(size=1, line=dict(width=0))) fig.show()
内容的提问来源于stack exchange,提问作者Leon
相关产品推荐
相关产品推荐

