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

如何在ggplot中实现基于类别概率的三色渐变散点图着色?

实现按类别区分且随归属概率渐变的ggplot散点图

核心思路

要同时实现类别区分和归属概率渐变,关键是给每个类别分配专属色相(比如绿、蓝、红),再通过归属概率(membership)调整颜色深浅——概率越高,颜色越深;概率越低,颜色越浅(接近白色)。

具体实现方法

方法1:手动计算每个点的颜色(推荐)

利用hcl颜色空间固定色相,通过membership调整亮度,直接生成每个点的颜色值:

library(ggplot2)
library(scales)

# 读入数据集(如果还没读入)
fuzzy.df <- read.delim("https://raw.githubusercontent.com/gunsnfloyd/algorithmdata/main/fuzzy.tsv", sep = "\t")

# 为每个类别定义对应色相(绿色=120,蓝色=240,红色=0)
category_hues <- c("1" = 120, "2" = 240, "3" = 0)

# 为每个点生成对应颜色:固定色相,membership越高,亮度越低(颜色越深)
fuzzy.df$point_color <- mapply(function(cat, mem) {
  hcl(h = category_hues[as.character(cat)], c = 100, l = 100 - mem * 50)
}, fuzzy.df$cat, fuzzy.df$membership)

# 绘制散点图
ggplot(fuzzy.df, aes(x = x1, y = x2, color = point_color)) +
  geom_point(size = 2) +  # 可按需调整点大小
  scale_color_identity(guide = "legend", 
                       labels = c("低归属概率", "中归属概率", "高归属概率"),
                       breaks = c(hcl(120, 100, 80), hcl(120, 100, 50), hcl(120, 100, 20))) +
  labs(x = "x1", y = "x2", color = "归属概率等级") +
  theme_minimal()

方法2:利用ggplot标度结合颜色渐变

为每个类别单独生成渐变颜色序列,通过interaction映射类别和归属概率的组合:

library(ggplot2)
library(scales)

fuzzy.df <- read.delim("https://raw.githubusercontent.com/gunsnfloyd/algorithmdata/main/fuzzy.tsv", sep = "\t")

# 为每个类别生成渐变颜色(浅到深)
green_gradient <- colorRampPalette(c("#e5f5e0", "#238b45"))(100)
blue_gradient <- colorRampPalette(c("#deebf7", "#08519c"))(100)
red_gradient <- colorRampPalette(c("#fee0d2", "#a50f15"))(100)

# 合并所有渐变颜色
all_colors <- c(green_gradient, blue_gradient, red_gradient)

# 绘制散点图,用cut将membership分成100个区间,结合类别生成交互项
ggplot(fuzzy.df, aes(x = x1, y = x2, color = interaction(cat, cut(membership, 100)))) +
  geom_point(size = 2) +
  scale_color_manual(values = all_colors) +
  labs(x = "x1", y = "x2", color = "类别 & 归属概率") +
  theme_minimal() +
  guides(color = guide_legend(ncol = 3))  # 调整图例列数,避免过于冗长

为什么之前的代码无法区分类别?

你之前用scale_color_gradientn(colors = rainbow(3))时,是把membership直接映射到彩虹色的整体渐变,完全忽略了类别信息——不同类别的点只要membership相同,就会显示相同颜色,自然无法区分类别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 12:56:21