Home > Blockchain >  How to color two opposite sides of plot?
How to color two opposite sides of plot?

Time:01-18

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!

CodePudding user response:

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
  )) 
  • Related