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):
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:
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: