Álv*_*gas 5 visualization r histogram ggplot2 tidyverse
我想使用 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)
Run Code Online (Sandbox Code Playgroud)
现在我得到这个:
尝试这种方法。您可以使用..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')
Run Code Online (Sandbox Code Playgroud)
输出:
如果您想避免排队,请尝试以下操作:
# 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')
Run Code Online (Sandbox Code Playgroud)
输出: