微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

仅对正常曲线下顶部区域的一部分进行着色

如何解决仅对正常曲线下顶部区域的一部分进行着色

我试图在正态曲线下的区域中进行着色,比如在一个标准偏差之间,但不是一直到 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")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。