简体   繁体   English

ggplot2 密度与多组和修剪 = TRUE:密度不 go 为 0?

[英]ggplot2 density with multiple groups and trim=TRUE: density does not go to 0?

I am plotting in ggplot2 densities for multiple groups that each have a different support.我正在为每个具有不同支持的多个组绘制ggplot2密度。 For this reason, I would like the density lines to stop at the min/max of the respective groups, to convey visually the difference in supports.出于这个原因,我希望密度线在各个组的最小值/最大值处停止,以直观地传达支撑的差异。 I can do this with ggvis , see:我可以用ggvis做到这一点,请参阅:

在此处输入图像描述

However, I am not able to do this nicely with geom_density() :但是,我无法用geom_density()很好地做到这一点:

  • By default ( trim=FALSE ) geom_density() will extend the lines of the density at 0, so that all densities overlap at 0, makes difficult to compare support默认情况下( trim=FALSEgeom_density()将在 0 处扩展密度线,因此所有密度在 0 处重叠,难以比较支持
  • Setting trim=TRUE , geom_density() does not extend the lines outside of the respective support, yet will trim the lines even over the y axis.设置trim=TRUEgeom_density()不会将线条延伸到相应支撑之外,但会在 y 轴上修剪线条。

How can I mimic the ggvis plot with ggplot::geom_density ?如何使用ggplot::geom_density模仿ggvis plot ?

Code代码

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

Created on 2021-03-31 by the reprex package (v1.0.0)代表 package (v1.0.0) 于 2021 年 3 月 31 日创建

A workaround could be to use the base density function and plot that as geom_line :一种解决方法是使用基本density function 和 plot 作为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")

Created on 2021-03-31 by the reprex package (v1.0.0)代表 package (v1.0.0) 于 2021 年 3 月 31 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM