使用ggforce::geom_mark_ellipse自定义填充色时图例消失求助
问题描述
尝试为绘图及图例设置自定义颜色,但运行代码后图例消失(见图1);当不使用自定义颜色填充椭圆时,图例可正常显示(见图2),求解决建议。
图1:自定义颜色后图例消失
图2:默认填充时图例正常显示
运行代码
library(palmerpenguins) library(tidyverse) library(ggplot2) library(ggforce) penguins <- penguins %>% drop_na() penguins %>% head() %>% print() cols <- c("#0066cc","#9933ff","#66cc33") my_color <- rep("", nrow(penguins)) cidx <- 0 for (color in unique(penguins$species)){ cidx <- cidx + 1 idx <- which(penguins$species == color) my_color[idx] <- cols[cidx] } p <- penguins %>% ggplot(aes(x = bill_length_mm, y = flipper_length_mm))+ geom_mark_ellipse(aes(fill = I(my_color), alpha = I(0.2)), # geom_mark_ellipse(aes(fill = species), expand = unit(0.5,"mm"), size = 0) + geom_point(color = I(my_color)) plot(p)
解决方法
问题出在你用I()直接传入颜色值,这会让ggplot把颜色当成常量而非映射变量,自然不会生成图例。正确的做法是保留基于species的映射,再通过自定义调色板替换默认颜色,这样既能保留图例,又能使用自定义颜色:
优化后的代码
library(palmerpenguins) library(tidyverse) library(ggplot2) library(ggforce) penguins <- penguins %>% drop_na() cols <- c("#0066cc","#9933ff","#66cc33") names(cols) <- unique(penguins$species) # 给颜色向量绑定物种名称,确保对应正确 p <- penguins %>% ggplot(aes(x = bill_length_mm, y = flipper_length_mm))+ geom_mark_ellipse(aes(fill = species), alpha = 0.2, expand = unit(0.5,"mm"), size = 0) + geom_point(aes(color = species)) + # 用species映射而非直接传颜色 scale_fill_manual(values = cols) + # 自定义椭圆填充色 scale_color_manual(values = cols) # 自定义点的颜色 plot(p)
关键说明
- 保留
aes(fill = species)和aes(color = species)的映射关系,让ggplot识别这是需要生成图例的分类变量 - 给自定义颜色向量绑定物种名称,确保每个物种对应正确的颜色
- 通过
scale_fill_manual()和scale_color_manual()替换默认配色,而非直接用I()强制传入常量
内容的提问来源于stack exchange,提问作者Wasim Aftab
相关产品推荐
相关产品推荐

