简体   繁体   中英

How to color two opposite sides of plot?

I'm trying to fill the rejection area under the plot for two-sided hypothesis by using the geom_plot.

library(ggplot2)
ggplot(data.frame(x = c(0:30)), aes(x = x)) +
  stat_function(fun = dnorm, 
                args = list(mean = 30 * 0.6, 
                            sd = sqrt(30 * 0.6 * (1 - 0.6))),
                aes(col = "H0")) +
  
  geom_area(stat = "function",
            fun = dnorm,
            args = list(mean = 30 * 0.6, 
                        sd = sqrt(30 * 0.6 * (1 - 0.6))),
            aes(fill = "alpha"),
            xlim = c(c(0,13), c(23,30))
            )
  

I tried giving xlim two vectors as arguments however it only takes the first one and fills only the area for x between 0 and 13 completely ignoring the second vector. Technically I could add the second geom_area two make it work, but I feel like it's counter-intuitive and it should be possible with only one geom_area function. Any ideas? Thanks in advance!

How about repeating the geom_area through lapply like this:

ggplot(data.frame(x = c(0:30)), aes(x = x)) +
  stat_function(fun = dnorm, 
                args = list(mean = 30 * 0.6, 
                            sd = sqrt(30 * 0.6 * (1 - 0.6))),
                aes(col = "H0")) +
  
  lapply(list(c(0,13), c(23,30)), function(x) 
    geom_area(stat = "function",
            fun = dnorm,
            args = list(mean = 30 * 0.6, 
                        sd = sqrt(30 * 0.6 * (1 - 0.6))),
            aes(fill = "alpha"),
            xlim = x
  )) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM