11

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 2

14

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') 

chart

Sign up to request clarification or add additional context in comments.

Comments

11
Answer recommended by R Language Collective

One option would be to add the annotation via the breaks= and labels= arguments of scale_y_continuous, i.e. add an additional break and respective label like so:

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, 6, 5.5),
    labels = c(0, 2, 4, 6, "High")
  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.