Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 annotate on y-axis (outside of plot)

Tags:

r

ggplot2

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!

like image 876
qnp1521 Avatar asked Dec 23 '22 18:12

qnp1521


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)

like image 192
stefan Avatar answered Jan 19 '23 01:01

stefan


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

like image 27
xilliam Avatar answered Jan 18 '23 23:01

xilliam