Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill area between two point-lines R

I have a tibble similar to the following one:

 Offensive <- tibble(OffenseFormation = c("A","B","C"),
                     yardas_mean = c(3,4,5),
                     yardas_min  = c(1,4,1),
                     yardas_max  = c(5,4,6))

I plot the lines with the following code (as you can see in the picture below):

 Offensive %>%
   pivot_longer(starts_with("yardas_"),names_to = "yardas") %>% 
   ggplot(aes(x = OffenseFormation, y = value, group = yardas)) +
   geom_line(aes(colour = yardas)) + 
   geom_point(aes(colour = yardas)) 

enter image description here

What I want is fill the area between yardas_min and yardas_max lines.

I've already used the following ggplot orders:

  • geom_area(alpha=0.1)

  • geom_polygon( aes(y = value, group = yardas), alpha = 0.1)

and also read some previous post like these ones:

  • https://mcfromnz.wordpress.com/2014/06/02/shading-between-two-lines-ggplot/

  • How to highlight area between two lines? ggplot

But no success, any help?

Thanks,

Alberto

like image 821
Alberto Torrejon Valenzuela Avatar asked Mar 28 '26 04:03

Alberto Torrejon Valenzuela


1 Answers

The issue is that you have discrete values as x axis. You can make a ribbon by adding continuous values in geom_ribbon:

Offensive %>%
  pivot_longer(starts_with("yardas_"),names_to = "yardas") %>% 
  ggplot(aes(x = OffenseFormation, y = value, group = yardas)) +
  geom_line(aes(colour = yardas))+
  geom_ribbon(data = Offensive, 
               inherit.aes = FALSE, 
               aes(x = 1:3, ymin = yardas_min, ymax = yardas_max), 
              fill = "grey70")+
  geom_line(aes(colour = yardas))+
  geom_point(aes(colour = yardas))

enter image description here

like image 190
dc37 Avatar answered Mar 29 '26 18:03

dc37



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!