﻿ 如何为几个正态分布下方的区域着色？ - 代码日志

如何为几个正态分布下方的区域着色？

``````x1<-50:200
a1<-dnorm(x1,134,20)
b1<-dnorm(x1,130,14)
c1<-dnorm(x1,132,12)
d1<-dnorm(x1,105,10)

scale<-range(pretty(range(a1,b1,c1,d1)))

remap<-function(x, to, from=range(x)) {
(x-from[1]) / (from[2]-from[1]) * (to[2]-to[1]) + to[1]
}

plot(NA, NA, xaxt="n", yaxt="n", type="n", xlim=scale, ylim=scale, xlab="Variable X", ylab="")
rect(remap(134-20, scale, range(x1)), scale[1],
remap(134+20, scale, range(x1)), scale[2], col="#ff606025")
rect(remap(130-14, scale, range(x1)), scale[1],
remap(130+14, scale, range(x1)), scale[2], col="#005ccd40")
rect(remap(132-12, scale, range(x1)), scale[1],
remap(132+12, scale, range(x1)), scale[2], col="#005ccd40")
rect(remap(105-10, scale, range(x1)), scale[1],
remap(105+10, scale, range(x1)), scale[2], col="#005ccd40")
#R1429
rect(remap(183, scale, range(x1)), scale[1],
remap(183, scale, range(x1)), scale[2], col="darkblue", lwd=3,lty=3)

lines(remap(x1,scale), a1, col="#ff6060", lwd=3)
lines(remap(x1,scale), b1, col="#005ccd", lwd=3, lty=3)
lines(remap(x1,scale), c1, col="#005ccd", lwd=3)
lines(remap(x1,scale), d1, col="#005ccd", lwd=3,lty=3)

axis(2);
axis(1, at=remap(pretty(x1), scale), pretty(x1))
``````

``````library(dplyr)
library(ggvis)

## -- data generation copied from @NickK -- ##
data.frame(group = letters[1:4],
m = c(130, 134, 132, 105),
s = c(20, 14, 12, 10)) %>%
group_by(group) %>%
do(data_frame(group = .\$group,
x = 50:200,
y = dnorm(x, .\$m, .\$s),
withinSd = abs(x - .\$m) <= .\$s)) %>%
## ---------------------------------------- ##
mutate(dash = ifelse(grepl("a|d", group), 5, 0),
color = ifelse(grepl("a|c|d", group), "blue", "red"))  %>%
ggvis() %>%
layer_paths(~x, ~y, stroke := ~color, strokeDash := ~dash) %>%
filter(withinSd) %>%
layer_ribbons(~x, ~y, y2 = ~y-y, fill := ~color, fillOpacity := 0.2) %>%
hide_legend("fill") %>%