Home > database >  geom_ribbon: Fill area between lines - spurious lines connecting groups
geom_ribbon: Fill area between lines - spurious lines connecting groups

Time:02-06

I'm trying to build a plot with two lines and fill the area between with geom_ribbon. I've managed to select a fill color (red/blue) depending on the sign of the difference between two lines. First I create two new columns in the dataset for ymax, ymin. It seems to work but some spurious lines appear joining red areas.

Is geom_ribbon appropriate to fill the areas? Is there any problem in the plot code?

This is the code used to create the plot

datos.2022 <- datos.2022 %>% mutate(y1 = SSTm-273.15, y2 = SST.mean.day-273.15)

datos.2022 %>% ggplot(aes(x=fecha))   
  geom_line(aes(y=SSTm-273.15), color = "red")  
  geom_line(aes(y=SST.mean.day - 273.15), color = "black")  
  geom_ribbon(aes(ymax=y1, ymin = y2, fill = as.factor(sign)), alpha = 0.6)  
  scale_fill_manual(guide = "none", values=c("blue","red"))  
  scale_y_continuous(limits = c(10,30))  
  scale_x_date(expand = c(0,0), breaks = "1 month", date_labels = "%b" )   
  theme_hc()   
  labs(x="",y ="SST",title = "Temperature (2022)")   
  theme(text = element_text(size=20,family = "Arial"))

And this is the output

enter image description here

Example data for the plot available at https://www.dropbox.com/s/mkk8w7py2ynuy1t/temperature.dat?dl=0

CodePudding user response:

What if you made two different series to plot as ribbons - one for the positive values where there is no distance between ymin and ymax for the places where the difference is negative. And one for the negative values that works in a similar way.

library(dplyr)
library(ggplot2)

datos.2022 <- datos.2022 %>% 
  mutate(y1 = SSTm-273.15, 
         y2 = SST.mean.day-273.15) %>% 
  rowwise() %>% 
  mutate(high_pos = max(SST.mean.day - 273.15, y1), 
         low_neg = min(SSTm-273.15, y2))


datos.2022 %>% ggplot(aes(x=fecha))   
  geom_line(aes(y=SSTm-273.15), color = "red")  
  geom_line(aes(y=SST.mean.day - 273.15), color = "black")  
  geom_ribbon(aes(ymax=high_pos, ymin = SST.mean.day - 273.15, fill = "b"), alpha = 0.6, col="transparent", show.legend = FALSE)  
  geom_ribbon(aes(ymax = SST.mean.day - 273.15, ymin = low_neg, fill = "a"), alpha = 0.6, col="transparent", show.legend = FALSE)  
  scale_fill_manual(guide = "none", values=c("blue","red"))  
  scale_y_continuous(limits = c(10,30))  
  scale_x_date(expand = c(0,0), breaks = "1 month", date_labels = "%b" )   
  #theme_hc()   
  labs(x="",y ="SST",title = "Temperature (2022)")   
  theme(text = element_text(size=20,family = "Arial"))

  • Related