Home > Software design >  How to color the area between two geom_smooth lines?
How to color the area between two geom_smooth lines?

Time:03-11

I have 3 columns in a data frame from which I want to create a visualisation with geom_smooth() :

ggplot(my_data_frame)  
  aes(x = fin_enquete,
      y = intentions,
      colour = candidat)  
  geom_point(alpha = 1/6,
             shape = "circle", 
             size = .5L)  
  geom_smooth(mapping = aes(y = erreur_inf),
              size = .5L,
              span = .42,
              se = F)  
  geom_smooth(mapping = aes(y = erreur_sup),
              size = .5L,
              span = .42,
              se = F)  
  geom_smooth(method = "loess",
              size = 1.5L,
              span = .42,
              se = F)  
  labs(x = "Date de fin d'enquête", 
       y = "Pourcentage d'intentions de vote")  
  theme_minimal()  
  theme(text = element_text(family = "DIN Pro"))  
  coord_cartesian(expand = F)  
  easy_remove_legend()

ggplot

CodePudding user response:

You could use lapply() smooth to calculate the range of df values such as (5,11,13) to calculate the smooths and plot only the two edges of the se.

Sample code:

      library(ggplot2)

ggplot(data = mtcars,
       mapping = aes(x = wt,
                     y = mpg))  
  geom_point(size = 2) 
  lapply(c(5,11, 13), function (i) {
  geom_smooth(
               data = ~ cbind(., facet_plots = i),
               method = lm,
               se=F,
               formula = y ~ splines::bs(x, i)
              ) 
  }) 
    #facet_wrap(vars(facet_plots))
  geom_ribbon( 
              stat = "smooth",
              method = "loess",
              se = TRUE,
              alpha = 0, # or, use fill = NA
              colour = "black",
              linetype = "dotted") 
  theme_minimal()

Plot:

enter image description here

  • Related