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

使用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)

关键说明

  1. 保留aes(fill = species)和aes(color = species)的映射关系,让ggplot识别这是需要生成图例的分类变量
  2. 给自定义颜色向量绑定物种名称,确保每个物种对应正确的颜色
  3. 通过scale_fill_manual()和scale_color_manual()替换默认配色,而非直接用I()强制传入常量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:20:33