0
我想突出顯示垂直線和正常分佈函數之間的區域。我知道它是如何與離散值一起工作的,但stat_function讓我感到困惑。代碼看起來像這樣:ggplot2:高亮區域取決於dnorm函數
library(ggplot2)
n1 <- 5
ggplot(data.frame(x = c(-2, 2)), aes(x)) +
stat_function(fun = dnorm, args = list(sd = 1/sqrt(n1))) +
geom_vline(xintercept = 0.5, linetype = "dashed", color = "red", size = 1) +
geom_vline(xintercept = -0.5, linetype = "dashed", color = "red", size = 1) +
ylim(c(0, 1.5)) +
theme_light() +
geom_rect(aes(xmin = 0.5, xmax = Inf, ymax = Inf, ymin = 0), fill = "grey", alpha = .3)
我知道我需要將ymax更改爲x> 0.5的值。問題是如何?
編輯: 我看着這個應該和我一樣的問題。當我重寫代碼他們的方式,在突出的作品,但它並沒有給我一個合適的正態分佈了,因爲你可以在這裏看到:
library(dplyr)
set.seed(123)
range <- seq(from = -2, to = 2, by = .01)
norm <- rnorm(range, sd = 1/sqrt(n1))
df <- data_frame(x = density(norm)$x, y = density(norm)$y)
ggplot(data_frame(values = norm)) +
stat_density(aes(x = values), geom = "line") +
geom_vline(xintercept = 0.5, linetype = "dashed", color = "red", size = 1) +
geom_vline(xintercept = -0.5, linetype = "dashed", color = "red", size = 1) +
ylim(c(0, 1.5)) +
theme_light() +
geom_ribbon(data = filter(df, x > 0.5),
aes(x = x, ymax = y), ymin = 0, fill = "red", alpha = .5)
當我堅持stat_function和使用geom_ribbon與子集爲在同一個問題中提出,它突出了越野車,你可以看到這裏:
ggplot(data_frame(x = c(-2, 2)), aes(x)) +
stat_function(fun = dnorm, args = list(sd = 1/sqrt(n1))) +
geom_vline(xintercept = 0.5, linetype = "dashed", color = "red", size = 1) +
geom_vline(xintercept = -0.5, linetype = "dashed", color = "red", size = 1) +
ylim(c(0, 1.5)) +
theme_light() +
geom_ribbon(data = filter(df, x > 0.5),
aes(x = x, ymax = y), ymin = 0, fill = "red", alpha = .5)
還不滿意。
看到此https://stackoverflow.com/questions/20355849/ggplot2-shade-area-under-density-curve-by-group [GGPLOT2遮陽面積 – Alice
可能的複製密度曲線下通過組](https://stackoverflow.com/questions/20355849/ggplot2-shade-area-under-density-curve-by-group) – Alice
https://github.com/Andryas/distShiny/blob/master/global.R <=看到這個。 –