5

I am trying to add text on the outside of my plot (using ggplot). The text will both be independent from the plot.

    A <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    B <- c(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
    C <- data.frame(A, B)

    ggplot(data = C) + geom_point(mapping = aes(x = A, y = B)) + 
labs(title = "Plot") + theme(plot.title = element_text(hjust = 0.5))

I want the plot to look something like this. I would like the box to be drawn around the variables if that is possible.

https://i.sstatic.net/p6d3V.png

2
  • It sounds like you want to include other text that is not a legend, correct? You might look here: magesblog.com/post/…
    – Jon Spring
    Commented Jan 19, 2019 at 23:31
  • Yes that is correct. I am not looking to make a legend. I want to insert a box to the right of the plot and slap some text into it.
    – Binx
    Commented Jan 19, 2019 at 23:49

1 Answer 1

4

You can add text and graphics with grobs. First of all you need some free space on the right hand side. That's possible when you expend the margin in your themes. The command here is: theme(plot.margin = unit(c(1,5,1,1),"cm")), afterwards you have to declare what you want to insert.

Plot with increased margin (well since the background is white, it's actually not possible to see the incresed margin... but it's there):

increased margin

In you case i inserted a table, since it's easier. You can insert text, tables or shapes with grobs. Let's define the table first:

mytable<-cbind(c("variable_1","variable_2","variable_3"),c(0.5,1.5,3.5))

with annotion_costum() ggplot lets you insert objects as graphics in plots. Since our margin is high enough, you can add the table outside the plot.

Plot with added table:

with table

As last step i drawed a rectangular around the table. The full code is:

library(gridExtra)
library(grid)
A <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
B <- c(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
C <- data.frame(A, B)

mytable<-cbind(c("variable_1","variable_2","variable_3"),c(0.5,1.5,3.5))
ggplot(data = C) + geom_point(mapping = aes(x = A, y = B)) + 
  labs(title = "Plot") + theme(plot.title = element_text(hjust = 0.5))+
  theme(plot.margin = unit(c(1,5,1,1),"cm"))+
  annotation_custom(tableGrob(mytable, rows=NULL), 
                    xmin=unit(11.5,"npc"),xmax = unit(14,"npc"),  ymin=3.7, ymax=7)
  grid.rect(x=unit(0.83,"npc"),y=unit(0.5,"npc") ,width = unit(0.22,"npc"), height = unit(0.16,"npc"), gp = gpar(lwd = 3, col="black", fill = NA))

Final picture:

final plot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.