R:使用 ggplot2 按组镜像直方图

R: by group mirrored histogram using ggplot2

我想使用 ggplot 按组 得到镜像直方图,如底部图片所示。

library(ggplot2)
data2 <- data.frame(
  type = c( rep("Top 1", n_segment),
            rep("Top 2", n_segment),
            rep("Bottom 1", n_segment),
            rep("Bottom 2", n_segment)),
  value = c( rnorm(n_segment, mean=5),
             rnorm(n_segment, mean=12),
             rnorm(n_segment, mean=-5),
             rnorm(n_segment, mean=-12))
)

# Represent it
data2 %>%
  ggplot( aes(x=value, fill=type)) +
  geom_density( color="#e9ecef", alpha=0.6) 

现在我得到这个:

但我想镜像如下:

试试这个方法。您可以使用 ..density.. 并围绕不同的数据子集调整 geom_density() 启用 data 选项并巧妙地过滤哪些值上升和下降。这里的代码:

library(ggplot2)
library(dplyr)
# Represent it
data2 %>%
  ggplot( aes(x=value, fill=type,group=type)) +
  geom_density(aes(y=-1*..density..),alpha=0.6,
               data = ~ subset(., type %in% c("Bottom 1","Bottom 2")))+
  geom_density(aes(y=..density..),alpha=0.6,
               data = ~ subset(., !type %in% c("Bottom 1","Bottom 2")))+
  ylab('density')

输出:

如果你想避免排队,试试这个:

# Represent it 2
data2 %>%
  ggplot( aes(x=value, fill=type,group=type)) +
  geom_density(aes(y=-1*..density..),alpha=0.6,color='transparent',
               data = ~ subset(., type %in% c("Bottom 1","Bottom 2")))+
  geom_density(aes(y=..density..),alpha=0.6,color='transparent',
               data = ~ subset(., !type %in% c("Bottom 1","Bottom 2")))+
  ylab('density')

输出: