我认为这应该很简单,但尽管网上有大量信息,我还是迷失了。
我的问题:我有一个数据点向量,我想为其绘制密度曲线,然后为曲线下方的区域着色以表示最高密度区间 (HDI)。当然,我正在努力实现这一目标ggplot2
包,特别是qplot()
,因为我的数据是向量,而不是数据框。
可重复的例子
library(ggplot2)
library(HDInterval)
## create data vector
set.seed(789)
dat <- rnorm(1000)
## plot density curve with qplot and mark 95% hdi
qplot(dat, geom = "density")+
geom_vline(aes(xintercept = c(hdi(dat))))
所以我明白了:
但我真正想要的是这样的:
有没有一种简单的方法可以实现这一点ggplot2::qplot
?
您可以使用 ggridges 包来完成此操作。诀窍是我们可以提供HDInterval::hdi
作为分位数函数geom_density_ridges_gradient()
,我们可以用它生成的“分位数”来填充。 “分位数”是下尾、中尾和上尾的数字。
作为一般建议,我建议不要使用qplot()
。它更可能会引起混乱,并且将向量放入小标题中并不需要付出很大的努力。
library(tidyverse)
library(HDInterval)
library(ggridges)
#>
#> Attaching package: 'ggridges'
#> The following object is masked from 'package:ggplot2':
#>
#> scale_discrete_manual
## create data vector
set.seed(789)
dat <- rnorm(1000)
df <- tibble(dat)
## plot density curve with qplot and mark 95% hdi
ggplot(df, aes(x = dat, y = 0, fill = stat(quantile))) +
geom_density_ridges_gradient(quantile_lines = TRUE, quantile_fun = hdi, vline_linetype = 2) +
scale_fill_manual(values = c("transparent", "lightblue", "transparent"), guide = "none")
#> Picking joint bandwidth of 0.227
Created on 2019-12-24 by the reprex package https://reprex.tidyverse.org (v0.3.0)
中的颜色scale_fill_manual()
按照三组的顺序,因此,例如,如果您只想对左尾进行着色,您可以写values = c("lightblue", "transparent", "transparent")
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)