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:
I would prefer something more like this:
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!
You don't need to be drawing a second plot. You can use
annotation_custom
to position grobs anywhere inside or outside the plotting area. The positioning of the grobs is in terms of the data coordinates. Assuming that "5", "10", "15" align with "cat1", "cat2", "cat3", the vertical positioning of the textGrobs is taken care of - the y-coordinates of your three textGrobs are given by the y-coordinates of the three data points. By default,ggplot2
clips grobs to the plotting area but the clipping can be overridden. The relevant margin needs to be widened to make room for the grob. The following (using ggplot2 0.9.2) gives a plot similar to your second plot:Simplier solution based on
grid
This is now straightforward with ggplot2 3.0.0, since now clipping can be disabled in plots by calling
coord_cartesian(clip = 'off')
, as in the example below.