Reputation: 2570
I stumbled upon a simple problem with the positioning of ggplot, I'm going to provide a very simple example, the real problem is much more complex so I'm looking for a reproductive solution, if possible in the ggplot environment.
names <- c("a","b","c","d")
days <- c(100,50,25,10)
dat <- data.frame(name=rep(names,days),date=as.Date(Sys.Date()-sum(days)+1):Sys.Date(),value=rep(days,days))
ggplot(dat,aes(x = date, group = name)) +
geom_line(aes(y=value,color=name)) +
geom_text(aes(max(date),value,label=value),vjust=0)
What I'm looking for is to position the text at the end of each line representing the group which max(date) should accomplish. I tried various group=name possibilitys but couldn't fix this inside ggplot.
Upvotes: 1
Views: 5426
Reputation: 13169
Does this help? I have generated a second dataset for the labels, as it's easier to aggregate (and have control over it yourself) and you only need to plot each label once.
library(dplyr)
dat_labels <- dat %>% group_by(name) %>% summarise(
label_position=max(date),
label_value=max(value)
)
ggplot(dat,aes(x = date, group = name)) +
geom_line(aes(y=value,color=name)) +
geom_text(data=dat_labels, aes(x=label_position, y=label_value,label=label_value),vjust=0)
Upvotes: 5