2

Hi I want to draw the space between two lines with red and blue( representing the anomalies), but I don't succeed to make it. Only blue anomaly is drawn.
Here is my code :

library(RCurl)
t <- getURL("https://raw.githubusercontent.com/vladamihaesei/weather_covid/master/Tab/UVanomaly.csv")## if can not download it, try manually 
t <- read.csv(text =t)
head(t)
ggplot(t, aes(x=data, y=uv1920)) + 
  geom_line(aes(y = uv1920)) + 
  geom_line(aes(y = uv01_19)) +
  geom_ribbon(data=subset(t, uv1920 <= uv01_19), 
              aes(ymin=uv1920,ymax=uv01_19), fill="blue") +
  #scale_y_continuous(expand = c(0, 0), limits=c(0,20)) +
  #scale_x_continuous(expand = c(0, 0), limits=c(0,5)) + 
  scale_x_date(date_breaks = "2 weeks", date_labels = "%d%b")+
  scale_fill_manual(values=c("red","blue"))

enter image description here

Matt
  • 7,255
  • 2
  • 12
  • 34
Alex.V
  • 45
  • 8

1 Answers1

2

One approach to get the space between the lines filled may look like so.

The basic idea is to split the data in periods which can be mapped on the group aes.

Unfortunately this is not a perfect solution. As you can see we get gaps at the intersection points. I've done something similar lately with a lot of manual work to fill the gaps but far less intersection points. Maybe someone else has a more general and feasible solution to tackle this issue.

t <- read.csv("https://raw.githubusercontent.com/vladamihaesei/weather_covid/master/Tab/UVanomaly.csv")

library(ggplot2)
library(dplyr)

t1 <- t %>% 
  mutate(date = as.Date(data1),
         diff = uv1920 <= uv01_19,
         period = cumsum(diff != lag(diff, default = TRUE)))
t1 %>% 
  ggplot(aes(x=date)) + 
  geom_line(aes(y = uv1920)) + 
  geom_line(aes(y = uv01_19)) +
  geom_ribbon(aes(ymin =uv1920, ymax=uv01_19, group = period, fill = diff)) +
  scale_x_date(date_breaks = "2 weeks", date_labels = "%d%b")+
  scale_fill_manual(values=c("red","blue"))

stefan
  • 90,330
  • 6
  • 25
  • 51