1

Is it possible in ggplot2 to replace a legend with a custom text? I know about annotate but I do not want to write into a chart but next to it (or below it) - exactly where a legend would be and do it in a reasonably simple way.

E.g. in this simple chart

library(data.table)
library(ggplot2)
library(ggrepel)

id <- c(1:10) 
x1 <- sample(1:10, 10, replace=T)
x2 <- sample(1:10, 10, replace=T)
x3 <- sprintf("Point.%d",id)
df<-data.frame(id,x1,x2,x3)
dt<-data.table(df)
setkeyv(dt,c("id"))

p<-ggplot(data=dt,aes(x1,x2))+geom_point()+geom_text_repel(aes(label=x3))+
ggtitle("Graph")+xlab("X")+ylab("Y")+theme_bw()
p

I would like to write something (short) about the chart next to it. I am afraid that this might not be easily possible in ggplot2 since it is beyond its purpose - but would help me a lot.

Phann
  • 1,283
  • 16
  • 25
Martin
  • 165
  • 1
  • 9
  • Have you seen this stack overflow [link](http://stackoverflow.com/questions/12409960/ggplot2-annotate-outside-of-plot). This question may be a duplicate. – steveb Aug 25 '16 at 14:25
  • No, I do not want to write inside the chart. Just some text next to the whole chart. I know about annotate but hope it could be a better way using the legend (somehow). – Martin Aug 25 '16 at 14:29
  • 1
    Other possibilities [here](http://stackoverflow.com/questions/32506444/ggplot-function-to-add-text-just-below-legend). – Henrik Aug 25 '16 at 14:29

1 Answers1

7

this might be the easiest way,

gridExtra::grid.arrange(ggplot2::ggplot(), right = "this is a note")

enter image description here

by default text is rotated 90 degrees, to overwrite this use a textGrob explicitly,

gridExtra::grid.arrange(ggplot2::ggplot(), right = grid::textGrob("this is a note"))

enter image description here

baptiste
  • 75,767
  • 19
  • 198
  • 294