首页 > 解决方案 > 具有多个组的ggplot2密度和trim = TRUE:密度不会变为0?

问题描述

我正在绘制ggplot2多个组的密度,每个组都有不同的支持。出于这个原因,我希望密度线在各个组的最小值/最大值处停止,以直观地传达支撑的差异。我可以这样做ggvis,请参阅:

在此处输入图像描述

但是,我不能很好地做到这一点geom_density()

我怎样才能模仿ggvis情节ggplot::geom_density

代码

library(tidyverse)
library(ggvis)
#> 
#> Attaching package: 'ggvis'
#> The following object is masked from 'package:ggplot2':
#> 
#>     resolution
library(patchwork)

df <- tibble(x1=truncnorm::rtruncnorm(500, -1, 1),
           x2=truncnorm::rtruncnorm(500, -1.5, 1.5),
           x3=rnorm(500)) %>% 
  gather(variable, value, everything())


pl_gg_trim <- ggplot(df, aes(x=value, color=variable))+
  geom_density(trim=TRUE) +
  ggtitle("trim=TRUE: lines don't go to 0")
pl_gg_notrim <- ggplot(df, aes(x=value, color=variable))+
  geom_density()+
  ggtitle("trim=FALSE: hard to understand support of values")



pl_ggvis <- ggvis(df, ~value, fill = ~variable) %>%
  group_by(variable) %>%
  layer_densities()

#does not work with reprex: pl_ggvis

pl_gg_notrim/pl_gg_trim

reprex 包于 2021-03-31 创建(v1.0.0)

标签: rggplot2ggvisdensity-plot

解决方案


一种解决方法可能是使用基本density函数并将其绘制为geom_line

library(tidyverse)
library(broom)
set.seed(123)
df <- tibble(x1=truncnorm::rtruncnorm(500, -1, 1),
             x2=truncnorm::rtruncnorm(500, -1.5, 1.5),
             x3=rnorm(500)) %>% 
  pivot_longer(everything(), names_to = "variable", values_to = "value")

df %>%
  nest(data=value) %>% 
  mutate(fit=map(data, ~density(.$value)), results=map(fit, tidy)) %>% 
  unnest(results) %>% 
  ggplot(aes(x, y, color=variable)) + 
  geom_line() +
  labs(x="value", y="density")

reprex 包于 2021-03-31 创建(v1.0.0)


推荐阅读