Force a Regular Plot Object into a Grob for Use in Grid.Arrange

force a regular plot object into a Grob for use in grid.arrange

you can try with gridGraphics

library(gridGraphics)

grab_grob <- function(){
grid.echo()
grid.grab()
}

plot(cars)
g <- grab_grob()
b <- ggplot(cars,aes(x=speed,y=dist))+geom_line()
grid.arrange(
b,g,
ncol=1
)

or, alternatively, use gridBase.

Adjust margins of grob object in r

You just use theme(plot.margin = ...) as you would in a ggplot:

library(ggplot2)
library(cowplot)

p1 <- ggplot(mtcars, aes(disp, mpg)) +
geom_point()
p2 <- ggplot(mtcars, aes(qsec, mpg)) +
geom_point()
p3 <- ggplot(mtcars, aes(disp, mpg)) +
geom_point()
p4 <- ggplot(mtcars, aes(qsec, mpg)) +
geom_point()
plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv")

Sample Image


plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv") +
theme(plot.margin = unit(c(20,20,20,20), "points"))

Sample Image

Created on 2020-04-29 by the reprex package (v0.3.0)

How to clip a grob into a grobTree object

try with clip = TRUE in viewport vp

Specify widths and heights of plots with grid.arrange

Try plot_grid from the cowplot package:

library(ggplot2)
library(gridExtra)
library(cowplot)
p1 <- qplot(mpg, wt, data=mtcars)
p2 <- p1
p3 <- p1 + theme(axis.text.y=element_blank(), axis.title.y=element_blank())
plot_grid(p1, p2, p3, align = "v", nrow = 3, rel_heights = c(1/4, 1/4, 1/2))

Sample Image

How to get hold of the base graphics plot.new to combine with others via arrangeGrob?

try this,

library(gridGraphics)
library(grid)
library(gridExtra)
library(ggplot2)

grab_grob <- function(...){
grid.echo(...)
grid.grab()
}

b <- grab_grob(function() plot(cars))
g <- ggplot()

grid.arrange(b, g)

Saving grid.arrange() plot to file

grid.arrange draws directly on a device. arrangeGrob, on the other hand, doesn't draw anything but returns a grob g, that you can pass to ggsave(file="whatever.pdf", g).

The reason it works differently than with ggplot objects, where by default the last plot is being saved if not specified, is that ggplot2 invisibly keeps track of the latest plot, and I don't think grid.arrange should mess with this counter private to the package.



Related Topics



Leave a reply



Submit