R – Labels inside ggplots using directlabels

Standard

The other day I generated the following figure with ggplot2

plot

using the following code:

ggplot(dat, aes(x = Year, y = log10(sum), group = id, colour = id)) +
 geom_point() +
 geom_smooth() +
 labs(x = "", y = "")

Note that I used the “group” argument to plot both curves on the same figure. Similarly I used the “colour” argument to colorize each curve differently.

But instead of a legend I wanted to have labels on or near the curves. To do that I resorted to the “directlabels” package.

First I needed to install it after installing its dependency package “quadprog” and load ggplot2 & directlabels:

install.packages("quadprog") # dependency for directlabels
install.packages("directlabels", repo="http://r-forge.r-project.org")

library(ggplot2)
library(directlabels) # load "directlabels"

To plot the figure, I went on as before but instead I assigned the plot command to “p” which I then passed on to direct.label().

p <- ggplot(dat, aes(x = Year, y = log10(sum), group = id, colour = id)) +
 geom_point() +
 geom_smooth() +
 labs(x = "", y = "")
direct.label(p)

As you can see the direct.label() function took care of the legend and replaced it with labels on the curves:

plot

This is a really useful package.

If you found this post helpful please give it a like or share it somewhere in the digital universe.

Advertisement