Home > Software design >  geom_vline for values over a threshold on Y-axis
geom_vline for values over a threshold on Y-axis

Time:06-09

I have a ggplot of temperature values plotted against time. I'd like to add vertical lines to my graph where temperature exceeds a threshold (let's say 12 degrees).

reprex:

#example data
Temp <- c(10.55, 11.02, 6.75, 12.55, 15.5)
Date <- c("01/01/2000", "02/01/2000", "03/01/2000", "04/01/2000", "05/01/2000")

#data.frame
df1 <- data.frame(Temp, Date)

#plot
df1%>%
  ggplot(aes(Date, format(as.numeric(Temp)))) 
  geom_line(group=1)

I thought I could maybe do something with geom_hline and then rotate 90 degrees. I went about this by trying to create an object of all values (to 2dp) between 12 and 20. I would then tell geom_hline to use that object to match values and draw the lines.

Then I get a bit stuck. I don't really know how to rotate the lines or whether that's even a good idea.

Disclaimer: I know my dates are not actually dates in the reprex, but they are in my rle.

CodePudding user response:

geom_vline can accept an xintercept either

  • in the xintercept parameter (if you want to specify it manually) or

  • in aes(xintercept = ...) if you want to use values from a data frame. We can use data = . %>% filter... to use the same data frame that came into ggplot, but apply some further manipulations.


df1 %>%
  mutate(Date = as.Date(Date, "%m/%d/%Y")) %>%
  ggplot(aes(Date, Temp))  
  geom_line()  
  geom_vline(data = . %>% filter(Temp > 12),
             aes(xintercept = Date))

enter image description here

  • Related