ggplot2 - annotate outside of plot

jslefche picture jslefche · Sep 13, 2012 · Viewed 73.3k times · Source

I would like to associate sample size values with points on a plot. I can use geom_text to position the numbers near the points, but this is messy. It would be much cleaner to line them up along the outside edge of the plot.

For instance, I have:

df=data.frame(y=c("cat1","cat2","cat3"),x=c(12,10,14),n=c(5,15,20))

ggplot(df,aes(x=x,y=y,label=n))+geom_point()+geom_text(size=8,hjust=-0.5)

Which produces this plot: enter image description here

I would prefer something more like this: enter image description here

I know I can create a second plot and use grid.arrange (a la this post) but it would be tedious to determine the spacing of the textGrobs to line up with the y-axis. Is there an easier way to do this? Thanks!

Answer

bschneidr picture bschneidr · Jul 12, 2018

This is now straightforward with ggplot2 3.0.0, since now clipping can be disabled in plots by using the clip = 'off' argument in coordinate functions such as coord_cartesian(clip = 'off') or coord_fixed(clip = 'off'). Here's an example below.

    # Generate data
    df <- data.frame(y=c("cat1","cat2","cat3"),
                     x=c(12,10,14),
                     n=c(5,15,20))

    # Create the plot
    ggplot(df,aes(x=x,y=y,label=n)) +
      geom_point()+
      geom_text(x = 14.25, # Set the position of the text to always be at '14.25'
                hjust = 0,
                size = 8) +
      coord_cartesian(xlim = c(10, 14), # This focuses the x-axis on the range of interest
                      clip = 'off') +   # This keeps the labels from disappearing
      theme(plot.margin = unit(c(1,3,1,1), "lines")) # This widens the right margin

enter image description here