Reputation: 2431
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))
Upvotes: 3
Views: 1197
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()
Upvotes: 3
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')
)
Upvotes: 4
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