Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

geom_vline for values over a threshold on Y-axis

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading