为Plotly散点图添加颜色渐变外的尺寸图例
实现Plotly散点图的双图例(颜色渐变+尺寸)
针对你的需求,Plotly默认仅为颜色映射生成渐变图例,尺寸映射的图例需要手动添加自定义轨迹实现,以下是具体方案:
核心实现代码
import plotly.express as px import plotly.graph_objects as go # 基于topic_stats2数据集绘制基础散点图 fig = px.scatter( topic_stats2, x="number_papers", y="total_citationCount", color="HHI", # 颜色映射HHI指标 size="scaled_avg_referenceCount", # 尺寸映射标准化平均参考文献数 color_continuous_scale="Viridis", # 可按需替换配色方案 size_max=60 # 控制标记最大尺寸,避免图表拥挤 ) # 生成尺寸图例:选取代表性尺寸值,添加隐形散点作为图例项 size_samples = [ topic_stats2["scaled_avg_referenceCount"].min(), round(topic_stats2["scaled_avg_referenceCount"].median(), 2), topic_stats2["scaled_avg_referenceCount"].max() ] for size_val in size_samples: fig.add_trace(go.Scatter( x=[None], y=[None], # 不显示在主图区域内 mode="markers", marker=dict( size=size_val, color="gray", # 颜色仅用于图例展示,不干扰主图 opacity=1 ), name=f"scaled_avg_ref: {size_val}", showlegend=True )) # 调整布局,优化双图例显示位置 fig.update_layout( legend=dict( orientation="h", yanchor="bottom", y=-0.25, xanchor="center", x=0.5 ), coloraxis_colorbar=dict( title="HHI", # 为颜色渐变条添加标题 x=1.05, y=0.5 ) ) fig.show()
关键说明
- 自定义尺寸图例:通过添加不显示在主图区域的散点轨迹,为每个代表性尺寸值创建图例项,清晰展示尺寸与
scaled_avg_referenceCount的对应关系 - 布局优化:将尺寸图例横向放置在图表底部,颜色渐变条固定在右侧,避免两个图例重叠
- 灵活性调整:可根据数据集分布调整
size_samples中的取值,或修改size_max控制标记的最大尺寸
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

