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

在facet_wrap分面图中解决geom_rect的alpha透明度失效问题

解决geom_rect中alpha参数不生效的问题

问题原因

你的数据框df中,每个Species分组下对应plq=2的行有大量重复的min和max值。geom_rect会为数据中的每一行绘制一个矩形,多个相同位置的半透明矩形叠加后,透明度被抵消,最终看起来就像没有设置alpha一样。

解决步骤

先对数据去重,只保留每个分面(Species)对应的唯一的min和max值,再用去重后的数据绘制矩形:

修改后的数据处理代码

library(dplyr)
library(ggplot2)

df <- iris %>% 
  filter(Species == "setosa" | Species == "versicolor") %>% 
  group_by(Species) %>% 
  mutate(plq = cut(Petal.Length,
                   quantile(Petal.Length, 
                            probs = seq(0, 1, 0.5)),
                   labels = seq(1:(length(seq(0, 1, 0.5)) - 1)), 
                   include.lowest = TRUE)) %>% 
  ungroup() %>% 
  group_by(Species, plq) %>% 
  mutate(max = max(Petal.Length), 
         min = min(Petal.Length)) %>% 
  ungroup() %>% 
  mutate(min = if_else(plq == 2, 
                       min, NA),
         max = if_else(plq == 2, 
                       max, NA)) %>%
  # 去重,保留每个Species对应的唯一有效min和max
  distinct(Species, min, max, .keep_all = FALSE) %>%
  # 过滤掉含NA的无效行
  filter(!is.na(min))

修改后绘图代码

df %>% 
  ggplot(aes(x = Petal.Length)) +
  stat_density(geom = "line", position = "identity", adjust = 3) +
  # 指定fill颜色让半透明效果更明显,同时使用去重后的数据
  geom_rect(aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf), 
            alpha = 0.2, fill = "gray") +
  facet_wrap(vars(Species)) +
  theme_classic()

说明

  • 去重后每个分面仅绘制一个矩形,alpha的半透明效果就能正常显示。
  • 额外指定fill参数(比如"gray")可以让半透明矩形的视觉效果更突出,默认黑色半透明可能不够明显。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:45:09