r - 具有多个组的ggplot2密度和trim = TRUE:密度不会变为0?
问题描述
我正在绘制ggplot2
多个组的密度,每个组都有不同的支持。出于这个原因,我希望密度线在各个组的最小值/最大值处停止,以直观地传达支撑的差异。我可以这样做ggvis
,请参阅:
但是,我不能很好地做到这一点geom_density()
:
- 默认情况下 (
trim=FALSE
)geom_density()
将在 0 处扩展密度线,使所有密度在 0 处重叠,难以比较支持 - 设置
trim=TRUE
,geom_density()
不会将线条延伸到相应支撑之外,但会在 y 轴上修剪线条。
我怎样才能模仿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)
解决方案
一种解决方法可能是使用基本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)
推荐阅读
- r - 得到 2 个向量的条件求和
- batch-file - 如果第一次发生鼠标移动,则只运行一次批处理脚本|批处理脚本|
- c# - 使用没有任何列键的 LINQ 从两个表中获取数据
- c++ - 为什么这个问题的时间复杂度只考虑前面的递归调用而不考虑整个问题?
- python - 错误:(-215:断言失败)总计 >= 0 &&(深度 == CV_32F || 深度 == CV_32S)在函数“cv::convexHull”中
- swiftui - SwiftUI 列表初始值设定项,已识别(作者:)
- python - 命令可以从终端或 bash 脚本中正常工作,但不能从使用子进程模块的 python 脚本中正常工作
- swift - 在 SwiftUI 视图上动画到 DragGesture 的 predictEndTranslation
- postgresql - 使用 tsl 与 pgbouncer 和 Postgres 的证书失败
- couchbase - 如何在 couchbase 服务器中执行查询