问题描述
我试图在正态曲线下的区域中进行着色,比如在一个标准偏差之间,但不是一直到 x 轴。我需要把它剪掉,只让曲线下方的顶部有阴影。在我下面的代码中,我想对正常曲线下的区域进行着色,但仅在 2 条虚线之间。任何人都可以帮忙吗?我见过很多例子,其中部分区域的阴影一直向下延伸到 x 轴。但是,我需要一些方法来阻止用户定义的曲线下方区域被着色。 谢谢, --院长。
library(ggplot2)
#generate a normal distribution plot
fig1 <- ggplot(data.frame(x = c(-4,4)),aes(x = x)) +
stat_function(fun = dnorm,args = list(mean=0,sd=1.25),colour = "darkblue",size = 1.25) +
theme_classic() +
geom_hline(yintercept = 0.32,linetype = "longdash") +
geom_hline(yintercept = 0.175,linetype = "longdash")
fig1
解决方法
您可以将 geom_polygon
与分布数据的子集/下限线一起使用。
library(ggplot2)
library(dplyr)
# make data.frame for distribution
yourDistribution <- data.frame(
x = seq(-4,4,by = 0.01),y = dnorm(seq(-4,1.25)
)
# make subset with data from yourDistribution and lower limit
upper <- yourDistribution %>% filter(y >= 0.175)
ggplot(yourDistribution,aes(x,y)) +
geom_line() +
geom_polygon(data = upper,aes(x=x,y=y),fill="red") +
theme_classic() +
geom_hline(yintercept = 0.32,linetype = "longdash") +
geom_hline(yintercept = 0.175,linetype = "longdash")