Reputation: 1599
I'm dealing a lot with geom_line plots these days. What is the easiest way to annotate on a plot with an axis of class date? Other than to convert the date variable to a different class?
Here's my code:
china_trades %>%
filter(type %in% c("Imports")) %>%
ggplot() +
geom_line(aes(x = month, y = dollars, group = 1)) +
theme_minimal()
I would like to annotate the last data point which is at 2017-10 and 48.
Upvotes: 2
Views: 3168
Reputation: 251
Maybe somebody can chime in with a pure gg way of doing this but the directlabels package has this functionality:
china_trades %>%
filter(type %in% c("Imports")) %>%
ggplot() +
geom_line(aes(x = month, y = dollars, group = 1)) +
theme_minimal() +
geom_dl(aes(label = month), method = list(dl.combine("last.points")))
Edit: Here's a gg way using annotate:
x <- as.Date(c('2016-1-1','2016-1-2','2016-1-3','2016-1-4'))
y <- c(4,1,2,3)
df <- data.frame(x,y)
lastDate<- max(x)
lastDateY <- df[x==lastDate,2]
ggplot(df) +
geom_line(aes(x = x, y = y)) +
annotate(geom='text', x=lastDate,y=lastDateY, vjust=-2, label="China")
Upvotes: 3