jjjjjj
jjjjjj

Reputation: 1172

ggplot: add multiline text annotation outside of plot

I want to add a textbox of 10 separate, stacked lines outside of my plot area in ggplot. My text is: t = c("a=1", "b=2", "c=3", ... , "j=10") but these labels are independent of the data.frame that I made my original ggplot. How can I add 10 lines outside of the plot area?

For example, I want to add a textbox around my vector t on the right of the following plot:

df = data.frame(y=rnorm(300), test=rep(c(1,2,3),each=100))
t = c("a=1", "b=2", "c=3", "d=4", "e=5", "f=6", "g=7", "h=8", "i=0", "j=10")
p <- ggplot(df, aes(x=factor(test), y=y))
p <- p + geom_violin() + geom_jitter(height=0, width=0.1)
p <- p + theme(legend.title=element_blank(), plot.margin=unit(c(0.1, 3, 0.1, 0.1), "cm"))
p

Upvotes: 2

Views: 2066

Answers (2)

eipi10
eipi10

Reputation: 93871

You can create a geom_text layer using the label values in t in order to get the labels printed as a legend. But we set alpha=0 in geom_text so that these labels won't be included in the plot, and we use legend.key=element_blank() and override.aes(list(size=0)) to get the "legend" labels (the t values) printed without the meaningless legend key.

p + 
  geom_text(data = data.frame(t, test=NA, y=NA), aes(label=t, colour=t), alpha=0, x=1, y=1) +
  theme(legend.key=element_blank(),
        legend.margin=margin(l=-10)) +
  guides(colour=guide_legend(override.aes=list(size=0)))

enter image description here

Upvotes: 3

baptiste
baptiste

Reputation: 77116

try

library(gridExtra)
grid.arrange(p, right = tableGrob(matrix(t,ncol=1),
             theme = ttheme_minimal(padding = unit(c(3,1),"line"))))

Upvotes: 4

Related Questions