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))
CodePudding user response:
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)
CodePudding user response:
Maybe you can use the patchwork
package, there's a
CodePudding user response:
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()