Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to arrange one grob object inside another with ggplot2 and gridExtra packages in r

I would like to know how to arrange one grob object (a table) inside another. Consider the following example:

library(ggplot2)
library(gridExtra)

p1 <- qplot(data=mtcars, x = mpg, y = hp, facets = ~ hp, geom="point")
t1 <- tableGrob(head(mtcars))
print(arrangeGrob(p1, t1))

This yields:

Plot 01

What I would like to do is place the table inside the other object like this:

Desired Result

Is this possible to do using gridArrange or perhaps some other methods from grid and/or gridExtra?

like image 277
JasonAizkalns Avatar asked Jan 21 '26 16:01

JasonAizkalns


1 Answers

Here is one possibility using grid functions:

png("SO.png", width = 1440, height = 720)

plot(p1)

vp <- viewport(x = 0.95, y = 0.02, 
               width = unit(0.4, "npc"), height = unit(0.2, "npc"),
               just = c("right", "bottom"))
pushViewport(vp)
grid.draw(t1)

dev.off()

resulting plot

like image 142
Roland Avatar answered Jan 23 '26 04:01

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!