After several tries, I finally could obtained a unique figure with several normal distributions. In those distributions, the 1sd was also drawn as vertical rectangles. The code I used is this one:
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))
I got the next figure after running the code:
But my question is: how can I color only the area below each normal distribution, instead of doing vertical rectangles?
It would be much easier to interpret.
Thanks in advance!
Here's another version using ggvis
:
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") %>%
add_axis("y", title_offset = 50)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With