R语言 在具有小平面和自由尺度的ggplot中查找y轴的中点

lbsnaicq  于 2024-01-03  发布在  其他
关注(0)|答案(2)|浏览(197)

我有一个带有自由刻度的面密度图,我想在上面覆盖一个geom_pointrange来表示分布的汇总。但是,我希望这个点固定在每个面的y轴中间(x根据汇总值而变化)。下面是我的代码:

  1. library(ggplot2)
  2. library(dplyr)
  3. data <- iris %>%
  4. mutate(grouping1 = rep(1:3, length.out = nrow(iris)),
  5. variable = Sepal.Length)
  6. data_summ <- data %>%
  7. group_by(grouping1) %>%
  8. summarise(variable = mean(Sepal.Length),
  9. lower = quantile(Sepal.Length, 0.025),
  10. upper = quantile(Sepal.Length, 0.975))
  11. ggplot(data) +
  12. geom_density(aes(x = variable,
  13. fill = grouping1)) +
  14. facet_wrap(~ grouping1, scales = "free")
  15. ## What I would like to add
  16. + geom_pointrange(data = data_summ,
  17. aes(x = variable,
  18. xmin = lower, xmax = upper,
  19. y = mid_y))

字符串
我的图看起来像这样:1
我希望结果是这样的:2
我尝试在构建ggplot后获得y轴limis,但还没有成功提取正确的值(可能是因为每个面都有多个grouping1变量?)另一个想法是创建一个辅助y轴并Map到该轴,但由于该轴需要基于原始轴进行转换,因此我仍然需要每个面的最大值.
任何想法将是真正的赞赏!

bxjv4tth

bxjv4tth1#

您可以先构建图,然后使用相应的插槽来找到中心:

  1. data <- iris %>%
  2. mutate(grouping1 = rep(1:3, length.out = nrow(iris)),
  3. variable = Sepal.Length)
  4. pl <- ggplot(data) +
  5. geom_density(aes(x = variable,
  6. fill = grouping1)) +
  7. facet_wrap(~ grouping1, scales = "free")
  8. plob <- ggplot_build(pl)
  9. data_summ <- data %>%
  10. group_by(grouping1) %>%
  11. summarise(variable = mean(Sepal.Length),
  12. lower = quantile(Sepal.Length, 0.025),
  13. upper = quantile(Sepal.Length, 0.975)) %>%
  14. mutate(mid_y = sapply(plob$layout$panel_scales_y, \(y) mean(y$get_limits())))
  15. pl + geom_pointrange(data = data_summ,
  16. aes(x = variable,
  17. xmin = lower, xmax = upper,
  18. y = mid_y))

字符串


的数据

展开查看全部
hmmo2u0o

hmmo2u0o2#

这对于当前的ggplot 2来说是一个痛苦的事情,然而,开发版本有一个很好的技巧来做相对的,数据不可知的放置。在开发版本中,你可以做y = I(0.5)来设置它在每个面板的垂直中间。

  1. # pak::pak("tidyverse/ggplot2") # installs development version of ggplot2
  2. library(ggplot2)
  3. library(dplyr)
  4. iris <- iris %>% mutate(grouping2=rep(c(1:3), length.out=nrow(iris)))
  5. data_summ <- iris %>%
  6. group_by(grouping2) %>%
  7. summarise(variable = mean(Sepal.Length),
  8. lower = quantile(Sepal.Length, 0.025),
  9. upper = quantile(Sepal.Length, 0.975))
  10. ggplot(iris) +
  11. geom_density(aes(x=Sepal.Length, fill=Species)) +
  12. geom_pointrange(
  13. data = data_summ,
  14. aes(x = variable, xmin = lower, xmax = upper, y = I(0.5))
  15. ) +
  16. facet_wrap(
  17. ~grouping2,
  18. scales="free"
  19. )

字符串
x1c 0d1x的数据
创建于2023-12-08带有reprex v2.0.2
(免责声明:我撰写了添加此内容的PR)

展开查看全部

相关问题