使用facet_wrap控制geom_rect上的Alpha

u3r8eeie  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(136)

我试图在一个多面图上得到部分透明的矩形。下面的例子说明了我所要做的,除了alpha参数不起作用:

  1. library(dplyr)
  2. library(ggplot2)
  3. df <- iris %>%
  4. filter(Species == "setosa" | Species == "versicolor") %>%
  5. group_by(Species) %>%
  6. mutate(plq = cut(Petal.Length,
  7. quantile(Petal.Length,
  8. probs = seq(0, 1, 0.5)),
  9. labels = seq(1:(length(seq(0, 1, 0.5)) - 1)),
  10. include.lowest = TRUE)) %>%
  11. ungroup() %>%
  12. group_by(Species, plq) %>%
  13. mutate(max = max(Petal.Length),
  14. min = min(Petal.Length)) %>%
  15. ungroup() %>%
  16. mutate(min = if_else(plq == 2,
  17. min, NA),
  18. max = if_else(plq == 2,
  19. max, NA))
  20. df %>%
  21. ggplot(aes(x = Petal.Length)) +
  22. stat_density(geom = "line", position = "identity", adjust = 3) +
  23. geom_rect(aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf), alpha = 0.2) +
  24. facet_wrap(vars(Species)) +
  25. theme_classic()

除了alpha参数不起作用之外,这个图正是我想要的。我找到了其他几个相关的问答(herehere),但我不认为其中任何一个直接适用于我的问题。

a14dhokn

a14dhokn1#

  1. library(dplyr)
  2. df_rect <- df %>%
  3. filter(!is.na(max)) %>%
  4. distinct(Species, max, min)
  5. df %>%
  6. ggplot(aes(x = Petal.Length)) +
  7. stat_density(geom = "line", position = "identity", adjust = 3) +
  8. geom_rect(aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf),
  9. inherit.aes = FALSE, # or put Petal.Length only in the stat_density layer
  10. data = df_rect, alpha = 0.2) +
  11. facet_wrap(vars(Species)) +
  12. theme_classic()

相关问题