R:使用ggplot2按组镜像直方图 [英] R: by group mirrored histogram using ggplot2

查看:47
本文介绍了R:使用ggplot2按组镜像直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ggplot来按组获得镜像的直方图,如下图所示.

I would like to get a mirrored histogram by group using ggplot as illustrated in the picture at the bottom.

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) 

现在我得到这个:

但是我想将它们镜像如下:

But I would like to mirror them as follows:

推荐答案

尝试这种方法.您可以使用 .. density .. 并围绕不同的数据子集调整 geom_density(),从而启用 data 选项并智能地过滤上升的值和向下.这里的代码:

Try this approach. You can work with ..density.. and adjust geom_density() around different subsets of data enabling data option and smartly filtering which values go up and down. Here the code:

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')

输出:

如果要避免行,请尝试以下操作:

If you want to avoid lines, try this:

# 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')

输出:

这篇关于R:使用ggplot2按组镜像直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆