Ggplot2 Annotate on Y-Axis (Outside of Plot)

Ggplot2 Annotate on Y-Axis (Outside of Plot)

I'm trying to add an annotation to the horizontal line on Y-axis. After reviewing similar questions, I created something similar, but not exactly what I want. Specifically, I want the text "High" to be placed on Y-axis (outside of the plot) below 6 (on the Y-axis). Here's what I've tried so far.

set.seed(57)
discharge <- data.frame(date = seq(as.Date("2011-01-01"), as.Date("2011-12-31"), by="days"),
                        discharge = rexp(365))

ggplot(discharge) +
  geom_line(aes(x = date, y = discharge)) +
  geom_hline(yintercept = 5.5, linetype= "dashed", color = "red") + 
  geom_text(aes(x = date[13], y = 5.5, label = "High"))

Any suggestions would be appreciated!

2 Answers

Set the breaks and labels accordingly. Try this:

library(ggplot2)

set.seed(57)
discharge <- data.frame(date = seq(as.Date("2011-01-01"), as.Date("2011-12-31"), by="days"),
                        discharge = rexp(365))

ggplot(discharge) +
  geom_line(aes(x = date, y = discharge)) +
  geom_hline(yintercept = 5.5, linetype= "dashed", color = "red") + 
  scale_y_continuous(breaks = c(0, 2, 4, 5.5, 6),
                     labels = c(0, 2, 4, "High", 6))

Created on 2020-03-08 by the reprex package (v0.3.0)

Here is an attempt at what you want that uses annotate (instead of geom_text) along with coord_cartesian with clip = "off", similar to the answer provided by Maurits Evers here: Add text outside plot area. Notice the xlim must be set for this to work and that the x-axis coordinate is set manually by subtracting from the date input.

ggplot(discharge) +
  geom_line(aes(x = date, y = discharge)) +
  geom_hline(yintercept = 5.5, linetype= "dashed", color = "red") + 
  annotate("text", x = discharge$date[13]-30, y = 5.5, label = "High")+
  coord_cartesian(xlim = c(discharge$date[13], max(discharge$date)),  clip = 'off') 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.