5

I'd like to annotate a plot and I'd like the note to be outside the plot area. I found this solution and it works for adding a note outside the plot area, but I cannot figure out how to change the label's appearance (most importantly, for my purpose, the font size).

Here is a minimal example from the aforementioned solution:

library (ggplot2)
library(grid)

df=data.frame(y=c("dog1","dog2","dog3"),x=c(12,10,14),n=c(5,15,20))
p <- ggplot(df, aes(x,y)) + geom_point()

# Add the annotation
p <- p + geom_text(aes(label = "Hello World!", x = 0, y = 0), vjust = 2, hjust = 1)

# Code to override clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

Ideally, the note would be in the bottom left corner.

Ole
  • 107
  • 3
  • 7
  • 2
    If you're using the example in the linked question (which uses `annotation_custom` and a `textGrob`), change the value of `cex` to change the font size. Instead of `cex` you can also use the `fontsize` parameter to set the font size in points. For example, instead of `cex=1.5`, do `fontsize=12` (or whatever size you prefer). For other parameters related to the text appearance, look at the help for `gpar`. – eipi10 Jun 17 '16 at 21:43
  • I prefer this approach: http://stackoverflow.com/a/17493256/471093 because turning clipping off can have unwanted consequences – baptiste Jun 17 '16 at 22:59

1 Answers1

3
library (ggplot2)
library(grid)

df=data.frame(y=c("dog1","dog2","dog3"),x=c(12,10,14),n=c(5,15,20))
p <- ggplot(df, aes(x,y)) + geom_point()

# Add the annotation
p <- p + geom_text(size=8, colour="red", aes(label = "Hello World!", x = 0, y = 0), vjust = 2.5, hjust = 1)

# Code to override clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)
Kurt_Brummert
  • 161
  • 1
  • 5
  • 2
    If you're not going to use `annotation_custom`, then you should create a new data frame for `geom_text`. Otherwise, "Hello World!" will be overplotted 3 times, once for each row of the parent data frame. That's why the annotation text looks jagged. You can show that the overplotting is occurring if you do `x=c(1,3,5)` in the call to `geom_text` to spread out the three copies of "Hello World!". – eipi10 Jun 17 '16 at 21:58
  • @eipi10: that was bugging me too. Thanks for the explanation. – Ole Jun 17 '16 at 22:35