Mil*_*les 3 r normal-distribution ggplot2 data-science
我找到了一种通过组合两个 geom_area 图来创建带有尾部区域的正态分布来“破解”ggplot的方法:
library(ggplot2)
mean <- 0
standard_deviation <- 1
Zscore <- -1.35
observation = (Zscore*standard_deviation) + mean
(tail_area <- round(pnorm(observation),2))
ggplot(NULL, aes(c(-5,5))) +
geom_area(stat = "function", fun = dnorm, fill="sky blue", xlim = c(-5, -1.35)) +
geom_area(stat = "function", fun = dnorm, xlim = c(-1.35, 5))
Run Code Online (Sandbox Code Playgroud)
是否有使用 ggplot 创建正态分布并像上面一样突出显示尾部区域的“不那么hackey”的方法?
首先,我喜欢你的方法;不确定这是否不那么“hackey”,但这是使用的另一种选择gghighlight
# Generate data (see comment below)
library(dplyr)
df <- data.frame(x = seq(-5, 5, length.out = 100)) %>% mutate(y = dnorm(x))
# (gg)plot and (gg)highlight
library(ggplot2)
library(gghighlight)
ggplot(df, aes(x, y)) + geom_area(fill = "sky blue") + gghighlight(x < -1.35)
Run Code Online (Sandbox Code Playgroud)
据我所知,gghighlight需要一个data论点,所以它不能单独使用geom_area(意思是:没有data但是有stat = "function"),或者有stat_function. 这就是我df首先生成数据的原因。
回应您关于如何“突出显示 1 和 -1 之间的区域”的评论;您可以执行以下操作
ggplot(df, aes(x, y)) + geom_area(fill = "sky blue") + gghighlight(abs(x) < 1)
Run Code Online (Sandbox Code Playgroud)
要突出显示该区域,1.5 < x < 2.5只需使用条件语句x > 1.5 & x < 2.5
ggplot(df, aes(x, y)) + geom_area(fill = "sky blue") + gghighlight(x > 1.5 & x < 2.5)
Run Code Online (Sandbox Code Playgroud)
抢占潜在的后续问题:此方法仅适用于连续区域。意思是,我还没有找到一种x < -2.5 & x > 2.5在单个gghighlight语句中突出显示的方法。