[英]ggplot2 density with multiple groups and trim=TRUE: density does not go to 0?
我正在为每个具有不同支持的多个组绘制ggplot2
密度。 出于这个原因,我希望密度线在各个组的最小值/最大值处停止,以直观地传达支撑的差异。 我可以用ggvis
做到这一点,请参阅:
但是,我无法用geom_density()
很好地做到这一点:
trim=FALSE
) geom_density()
将在 0 处扩展密度线,因此所有密度在 0 处重叠,难以比较支持trim=TRUE
, geom_density()
不会将线条延伸到相应支撑之外,但会在 y 轴上修剪线条。 如何使用ggplot::geom_density
模仿ggvis
plot ?
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
由代表 package (v1.0.0) 于 2021 年 3 月 31 日创建
一种解决方法是使用基本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")
由代表 package (v1.0.0) 于 2021 年 3 月 31 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.