You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotnine:颜色刻度、图例异常及默认调色板恢复求助

解决plotnine聚类散点图调色板恢复问题

问题背景

将聚类标签cluster转为分类变量后,图例可正常显示全部独立聚类项,但plotnine自动切换为离散调色板,偏离了原整数连续变量时的默认调色板风格。需要在保留离散图例的同时,恢复原默认调色板。


方案1:复用默认连续调色板的离散版本

plotnine默认连续填充调色板基于viridis系列,直接调用scale_fill_viridis_d()即可让分类变量使用同系列的离散调色板,风格与原连续版本一致:

# 先将cluster转为分类变量,确保图例显示独立聚类项
data = data.assign(cluster=pd.Categorical(data['cluster']))

frame_172_region_plot = (ggplot(data,
                    aes(x='x',y='y',fill='cluster'))
 + geom_point(size=3,alpha=1,stroke=0)
 + theme_bw()
 + theme(
         legend_position=(.5, 0.05), legend_direction='horizontal'
         , figure_size=(18.60, 13.96)
         , dpi= 300
         , axis_title=element_text(size=16)
        )
 + guides(fill=guide_legend(override_aes={"size": 6}))
 + scale_x_continuous(limits = (0,1860), expand = (0, 0), name='')
 + scale_y_continuous(limits = (0,1396), expand = (0, 0), name='')
 + labs(title='All Variables: Unlabeled Clusters. (Frame: 172, Sample: COL3)')
 + scale_fill_viridis_d()  # 添加此行,匹配原默认调色板风格
)

方案2:手动映射原连续调色板的精确颜色

如果需要严格对应原连续变量时的颜色(每个聚类整数标签对应连续刻度的颜色),可以通过以下方式生成并绑定颜色:

from plotnine.scales.scale_continuous import scale_fill_continuous

# 转为分类变量
data = data.assign(cluster=pd.Categorical(data['cluster']))
# 获取默认连续填充调色板的颜色生成函数
palette_func = scale_fill_continuous().palette
# 获取排序后的聚类整数标签
sorted_clusters = sorted(data['cluster'].cat.categories.astype(int))
# 根据聚类数量生成对应颜色
cluster_colors = palette_func(len(sorted_clusters))
# 创建标签-颜色映射字典
color_mapping = {str(cluster): cluster_colors[i] for i, cluster in enumerate(sorted_clusters)}

frame_172_region_plot = (ggplot(data,
                    aes(x='x',y='y',fill='cluster'))
 + geom_point(size=3,alpha=1,stroke=0)
 + theme_bw()
 + theme(
         legend_position=(.5, 0.05), legend_direction='horizontal'
         , figure_size=(18.60, 13.96)
         , dpi= 300
         , axis_title=element_text(size=16)
        )
 + guides(fill=guide_legend(override_aes={"size": 6}))
 + scale_x_continuous(limits = (0,1860), expand = (0, 0), name='')
 + scale_y_continuous(limits = (0,1396), expand = (0, 0), name='')
 + labs(title='All Variables: Unlabeled Clusters. (Frame: 172, Sample: COL3)')
 + scale_fill_manual(values=color_mapping)  # 绑定自定义颜色映射
)

说明

  • 转为分类变量是必须步骤,确保plotnine将聚类识别为离散分组,从而显示完整的独立图例项
  • 方案1操作简单,适合大多数场景,viridis系列的离散版本与原连续版本视觉风格统一
  • 方案2可精确匹配原连续刻度下的颜色,适合对颜色一致性有严格要求的场景

内容的提问来源于stack exchange,提问作者Ian Dryg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:50:31