I am going out on a limb here, but since in essence all of those plots are ggplot, could this work?
Update, now with working code:
First I created a ggbio simple plot. Using str(
p.ideo
)
one can see in which slot the ggplot object is, and retrieve it (I love str):
library("ggbio")
load(system.file("data", "hg19IdeogramCyto.rda", package="biovizBase", mustWork=TRUE))
p.ideo <- plotIdeogram(hg19IdeogramCyto, "chr1")
p.gg <- p.ideo@ggplot
Next I generated 2 simple ggplots:
dat <- data.frame(
time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)
p.bar <- ggplot(data=dat, aes(x=time, y=total_bill)) +
geom_bar(stat="identity")
p.line <- ggplot(data=dat, aes(x=time, y=total_bill, group=1)) +
geom_line()
And simply create the function and plot them together:
# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols: Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
multiplot(p.bar, p.line, p.gg, cols=1)
As a test, plotting the original ggbio object does indeed take over the plotting window:
multiplot(p.bar, p.line, p.ideo, cols=1)
sources:
ggbio
R cookbook
Unfortunately not, it renders the first two plots (ggplot2 objects), then the ggbio plot takes over and displays across the whole window. Thanks for the suggestion though
Could it be because the print call of ggbio is updating the plotting window? I have updated my answer with code that will plot 2 ggplots + 1 ggbio in 3 rows.
Did not know there was an @ggplot accessor method for ggbio objects! Thanks for that, solves a lot of problems!
I didn't know either until I started poking around with str().
great, I just know the
ggplot
slot fromggbio
. further that, Now we can combine plots using likecowplot::plot_grid()