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")
plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv") +
theme(plot.margin = unit(c(20,20,20,20), "points"))
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))
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
Mutate Multiple/Consecutive Columns (With Dplyr or Base R)
Vary the Color Gradient on a Scatter Plot Created with Ggplot2
Adding a Simple Lm Trend Line to a Ggplot Boxplot
How to Ignore Na in Ifelse Statement
Order X Axis Day Values in Ggplot2
Harvest (Rvest) Multiple HTML Pages from a List of Urls
How to Merge Two Nodes into a Single Node Using Igraph
Loop Through a Series of Qplots
Connect Ggplot Boxplots Using Lines and Multiple Factor
Rbindlist Data.Tables with Different Number of Columns
Dplyr - Mutate Dynamically Named Variables Using Other Dynamically Named Variables
Insert Function Variable into Graph Title
How to Split Data Frame by Column Names in R
How Is J() Function Implemented in Data.Table
How to Use With/Within Inside a Function