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

lbsnaicq  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(53)

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

library(ggplot2)
library(dplyr)

data <- iris %>% 
  mutate(grouping1 = rep(1:3, length.out = nrow(iris)),
         variable = Sepal.Length) 

data_summ <- data %>% 
  group_by(grouping1) %>% 
  summarise(variable = mean(Sepal.Length), 
            lower = quantile(Sepal.Length, 0.025), 
            upper = quantile(Sepal.Length, 0.975))

ggplot(data) +
  geom_density(aes(x = variable,
                   fill = grouping1)) +
  facet_wrap(~ grouping1, scales = "free")

## What I would like to add
+ geom_pointrange(data = data_summ,
                  aes(x = variable,
                      xmin = lower, xmax = upper,
                      y = mid_y))

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

bxjv4tth

bxjv4tth1#

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

data <- iris %>% 
  mutate(grouping1 = rep(1:3, length.out = nrow(iris)),
         variable = Sepal.Length)
pl <- ggplot(data) +
  geom_density(aes(x = variable,
                   fill = grouping1)) +
  facet_wrap(~ grouping1, scales = "free")

plob <- ggplot_build(pl)
data_summ <- data %>% 
  group_by(grouping1) %>% 
  summarise(variable = mean(Sepal.Length), 
            lower = quantile(Sepal.Length, 0.025), 
            upper = quantile(Sepal.Length, 0.975)) %>%
  mutate(mid_y = sapply(plob$layout$panel_scales_y, \(y) mean(y$get_limits())))

pl + geom_pointrange(data = data_summ,
                  aes(x = variable,
                      xmin = lower, xmax = upper,
                      y = mid_y))

字符串


的数据

hmmo2u0o

hmmo2u0o2#

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

# pak::pak("tidyverse/ggplot2") # installs development version of ggplot2
library(ggplot2)
library(dplyr)

iris <- iris %>% mutate(grouping2=rep(c(1:3), length.out=nrow(iris))) 
data_summ <- iris %>% 
  group_by(grouping2) %>% 
  summarise(variable = mean(Sepal.Length), 
            lower = quantile(Sepal.Length, 0.025), 
            upper = quantile(Sepal.Length, 0.975)) 

ggplot(iris) + 
  geom_density(aes(x=Sepal.Length, fill=Species)) + 
  geom_pointrange(
    data = data_summ,
    aes(x = variable, xmin = lower, xmax = upper, y = I(0.5))
  ) +
  facet_wrap(
    ~grouping2, 
    scales="free"
  )

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

相关问题