anderwyang
anderwyang

Reputation: 2431

In R grid package , how to use viewport for merge ggplot2 plots

I want to merge geom_point() and geom_boxplot() into one plot as attached image.Below code can't work.Anyone can help on this? Thanks!

library(grid)
library(ggplot2)
grid.newpage()
vp <- viewport(x=0.5,y=0.5,width = 1,height = 1)
push.Viewport(vp)
ggplot(mtcars) + geom_point(aes(mpg, disp))

vp_sub <- viewport(x=0.5,y=0.7,width=0.3,height=0.3)
push.viewport(vp_sub)
ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

enter image description here

Upvotes: 3

Views: 1197

Answers (3)

TarJae
TarJae

Reputation: 78927

Using viewport you could accomplish your task this way. If you want to save in a png then just comment out the line #png("my_plot.png")

library(grid)
library(ggplot2)
grid.newpage()

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))


vp <- viewport(x=0.5,y=0.5,width = 1,height = 1)vp_sub <- viewport(x=0.73,y=0.8,width=0.4,height=0.3)

#png("my_plot.png")
print(p1, vp=vp)
print(p2, vp=vp_sub)
dev.off()

enter image description here

Upvotes: 3

benson23
benson23

Reputation: 19097

Maybe you can use the patchwork package, there's a section that describes your problem exactly.

library(tidyverse)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

p1 + inset_element(
  p2, 
  left = 0.5, 
  bottom = 0.5, 
  right = unit(1, 'npc') - unit(1, 'cm'), 
  top = unit(1, 'npc') - unit(1, 'cm')
)

patchwork_insert_element

Upvotes: 4

stefan
stefan

Reputation: 124213

Besides patchwork::inset_element a second option would be to add your boxplot via ggplot2::annotation_custom. However, in contrast to patchwork::inset_element you have to set the positions in absolute coordinates of the data range of your main plot:

library(ggplot2)

bp <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

base <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp)) 

base +
  annotation_custom(grob = ggplotGrob(bp), xmin = 22.5, ymin = 250)

Upvotes: 4

Related Questions