I recognize that this question is a close duplicate of this one, but the solution there no longer works (using method="last.qp"
), so I'm asking it again.
The basic issue is that I'd like to use directlabels
(or equivalent) to label smoothed means for each group (from stat_smooth()
), rather than the actual data. The example below shows as close as I've gotten, but the labels aren't recognizing the grouping, or even the smoothed line. Instead, I'm getting the label at the last point. What I'd like is colour-coordinated text at the end of each smoothed line, rather than the legend on the right of the plot.
Here's an example:
library(ggplot2)
library(directlabels)
## Data
set.seed(10)
d <- data.frame(x=seq(1,100,1), y=rnorm(100, 3, 0.5))
d$z <- ifelse(d$y>3,1,0)
## Plot
p <- ggplot(d, aes(x=x, y=y, colour=as.factor(z))) +
stat_smooth(inherit.aes=T, se=F, span=0.8, show.legend = T) +
geom_line(colour="grey50") +
scale_x_continuous(limits=c(0,110)) +
geom_dl(label="text", method="maxvar.points", inherit.aes=T)
p
You need to tell
geom_dl
what you want to appear on you plot. The code below should simply address your needs;If you want different text rather than
0
and1
you just need to make it based ond$z
and put that instead ofas.factor(d$z)
.In order to put the labels beside last point of
geom_smooth
rather than last datapoints, I could not find any of the method ingeom_dl
to do so, therefore, came up with a workaround:A solution using
ggrepel
package based on this answerCreated on 2018-06-11 by the reprex package (v0.2.0).