R: gridExtra - How to plot a Summary as table? - r

I'm having trouble plotting a simple summary.
library(gridExtra)
SummaryTable <- summary(s.tvs$precio.nuevo)
grid.table(SummaryTable)
Gives me this:
I want to achieve something like this:

Upgrade comment:
grid.table calls tableGrob.
grid.table
#function (...)
#grid.draw(tableGrob(...))
#<environment: namespace:gridExtra>
From ?tableGrob its first argument is a matrix or data.frame. t coerces the named vector returned by summary to a matrix with dimension one row. Alternatively, you could of used as.matrix to produce a matrix with one column.
grid.newpage()
grid.table(t(summary(mtcars$mpg)))
grid.newpage()
grid.table(as.matrix(summary(mtcars$mpg)))
From comment:
Question:
I'm trying to plot a barplot and the table generated in this answer. I get: Error in gList(list(grobs = list(list(x = 0.5, y = 0.5, width = 1, height = 1, : only 'grobs' allowed in "gList" when using this code: grid.arrange(a, tbl, ncol = 1)
To combine different tables / plots using grid.arrange they need to be grobs (grid GRaphcal OBjects). So you cannot pass the results from grid.table to grid.arrange as it is not a grob (it actually plots the tableGrob directly). For this you need to pass the tableGrob.
So for example:
mybar <- qplot(mtcars$mpg, geom="bar")
tbl <- tableGrob(t(summary(mtcars$mpg)))
grid.newpage()
grid.arrange(mybar, tbl)

Related

how to plot multiplot (two columns plots) per page in a single pdf?

I am using ggplot and ggplot.multiplot function to plot multiplots (2 columns plots) per page but I couldnt make it. please help
I have a list of ggplots in variable plot_list and using function ggplot2.multiplot to plot 2 plot per page. But it plot all figures in one page that messed up. I want two plot per page in single figure.
>plot_list ## ggplot saved in a list though i have long list to plot
[[1]]
[[2]]
[[3]]
[[4]]
In both case i tried but all four plots plotted in same page:
library(easyGgplot2)
library(ggplot2)
ggplot2.multiplot(plotlist = plot_list, cols=2)
ggplot2.multiplot(plotlist = plot_list)
However its work as:
ggplot2.multiplot(plot_list[[1]],plot_list[[2]],cols=2)
ggplot2.multiplot(plot_list[[3]],plot_list[[4]],cols=2)
But i have long list of figures to generate in a single pdf !!
I also i have tried library("cowplot") but got error while using list of figures.
plot_grid(plot_list, ncol = 2, nrow = 1)
Error in ggplot_to_gtable(x) :
Argument needs to be of class "ggplot" or "gtable"
Please help.
Thanks
there's gridExtra::marrangeGrob
library(ggplot2)
library(gridExtra)
pl <- replicate(5, ggplot(), simplify=FALSE)
ml <- marrangeGrob(pl, nrow=1, ncol=2)
ggsave("multipage.pdf", ml)
for your cowplot problem, there is an argument plotlist in the plot_grid function (https://rdrr.io/cran/cowplot/man/plot_grid.html):
plot_grid(plotlist=plot_list)
should work

ggplot2 : printing multiple plots in one page with a loop

I have several subjects for which I need to generate a plot, as I have many subjects I'd like to have several plots in one page rather than one figure for subject.
Here it is what I have done so far:
Read txt file with subjects name
subjs <- scan ("ListSubjs.txt", what = "")
Create a list to hold plot objects
pltList <- list()
for(s in 1:length(subjs))
{
setwd(file.path("C:/Users/", subjs[[s]])) #load subj directory
ifile=paste("Co","data.txt",sep="",collapse=NULL) #Read subj file
dat = read.table(ifile)
dat <- unlist(dat, use.names = FALSE) #make dat usable for ggplot2
df <- data.frame(dat)
pltList[[s]]<- print(ggplot( df, aes(x=dat)) + #save each plot with unique name
geom_histogram(binwidth=.01, colour="cyan", fill="cyan") +
geom_vline(aes(xintercept=0), # Ignore NA values for mean
color="red", linetype="dashed", size=1)+
xlab(paste("Co_data", subjs[[s]] , sep=" ",collapse=NULL)))
}
At this point I can display the single plots for example by
print (pltList[1]) #will print first plot
print(pltList[2]) # will print second plot
I d like to have a solution by which several plots are displayed in the same page, I 've tried something along the lines of previous posts but I don't manage to make it work
for example:
for (p in seq(length(pltList))) {
do.call("grid.arrange", pltList[[p]])
}
gives me the following error
Error in arrangeGrob(..., as.table = as.table, clip = clip, main = main, :
input must be grobs!
I can use more basic graphing features, but I d like to achieve this by using ggplot. Many thanks for consideration
Matilde
Your error comes from indexing a list with [[:
consider
pl = list(qplot(1,1), qplot(2,2))
pl[[1]] returns the first plot, but do.call expects a list of arguments. You could do it with, do.call(grid.arrange, pl[1]) (no error), but that's probably not what you want (it arranges one plot on the page, there's little point in doing that). Presumably you wanted all plots,
grid.arrange(grobs = pl)
or, equivalently,
do.call(grid.arrange, pl)
If you want a selection of this list, use [,
grid.arrange(grobs = pl[1:2])
do.call(grid.arrange, pl[1:2])
Further parameters can be passed trivially with the first syntax; with do.call care must be taken to make sure the list is in the correct form,
grid.arrange(grobs = pl[1:2], ncol=3, top=textGrob("title"))
do.call(grid.arrange, c(pl[1:2], list(ncol=3, top=textGrob("title"))))
library(gridExtra) # for grid.arrange
library(grid)
grid.arrange(pltList[[1]], pltList[[2]], pltList[[3]], pltList[[4]], ncol = 2, main = "Whatever") # say you have 4 plots
OR,
do.call(grid.arrange,pltList)
I wish I had enough reputation to comment instead of answer, but anyway you can use the following solution to get it work.
I would do exactly what you did to get the pltList, then use the multiplot function from this recipe. Note that you will need to specify the number of columns. For example, if you want to plot all plots in the list into two columns, you can do this:
print(multiplot(plotlist=pltList, cols=2))

How to create plots dynamically in grid.arrange in R?

I have a function get.single.plot, which takes one character argument and returns a ggplot2 plot object. I would like to build a grid.arrange object with n plots on it, where the n is the size of vector of (mentioned) character arguments.
E.g., I woould like something like this to work:
character.argument.vector <- c("12", "1", "2")
grid.arrange(unlist(lapply(character.argument.vector, function(n) get.single.plot(n))),
ncol = 1)
Such thing does not work - I receive the following information:
Error in arrangeGrob(..., as.table = as.table, clip = clip, main = main, :
input must be grobs!
How should I do it?
With gridExtra v>=2.0 you can simply pass a list of grobs (or plots) to grid.arrange,
grid.arrange(grobs = lapply(...), ncol=1)

Combine phylogenetic tree with x,y graph

I'm trying to arrange a phylogenetic tree onto a graph showing physiological data for a set of related organisms. Something like the picture below. This was put together in powerpoint from 2 separate graphs. I guess it gets the job done, but I was hoping to create a single image which I think will be easier to format into a document. I am able to produce the graph I want using ggplot2, and import the tree using ape. I was thinking there should be a way to save the tree as a graphical object and then arrange it with the graph using the gridarrange function in gridExtra. The problem is that ape won't let me save the tree as a graphical object, e.g.,
p2<-plot(tree, dir = "u", show.tip.label = FALSE)
just plots the tree and when you call p2 it just gives a list of arguments. I'm wondering if anyone has any tips.
Thanks!
I'm not sure if that will work with gtable from CRAN
require(ggplot2)
require(gridBase)
require(gtable)
p <- qplot(1,1)
g <- ggplotGrob(p)
g <- gtable_add_rows(g, unit(2,"in"), nrow(g))
g <- gtable_add_grob(g, rectGrob(),
t = 7, l=4, b=7, r=4)
grid.newpage()
grid.draw(g)
#grid.force()
#grid.ls(grobs=F, viewports=T)
seekViewport("layout.7-4-7-4")
par(plt=gridPLT(), new=TRUE)
plot(rtree(10), "c", FALSE, direction = "u")
upViewport()
first I'd like to thanks baptiste for ALL his multiple answers that solved most of my issues with ggplot2.
second, I had a similar question which was to include a tree from ape inside a heatmap obtained with ggplot2. Baptiste made my day, and though my simplified version could help.
I used only what was useful for me (removing the addition of gg_rows).
library(ape)
tr <- read.tree("mytree.tree")
# heat is the heatmap ggplot, using geom_tile
g <- ggplotGrob(heat)
grid.newpage()
grid.draw(g)
# use oma to reduce the tree so it fits
par(new = TRUE, oma = c(5, 4, 5, 38))
plot(tr)
nodelabels(tr$node.label, cex = 1, frame = "none", col = "black", adj = c(-0.3, 0.5))
add.scale.bar()
# use dev.copy2pdf and not ggsave
dev.copy2pdf(file = "heatmap_prob.pdf")
the result is here

R - save multiplot to file

I’d really appreciate your help with the following problem. I know several ways to save a single plot to a file. My question is: How do I correctly save a multiplot to a file?
To begin with, I’m not an experienced R user. I use ggplot2 to create my plots, and another thing I should probably mention is that I use the RStudio GUI. Using an example from the R Cookbook, I'm able to create multiple plots in one window.
I would like to save this so-called multiplot to a file (preferably as jpeg), but somehow fail to do this.
I’m creating the multiplot as follows:
##define multiplot function
multiplot <- function(..., plotlist=NULL, cols) {
require(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# Make the panel
plotCols = cols # Number of columns of plots
plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
vplayout <- function(x, y)
viewport(layout.pos.row = x, layout.pos.col = y)
# Make each plot, in the correct location
for (i in 1:numPlots) {
curRow = ceiling(i/plotCols)
curCol = (i-1) %% plotCols + 1
print(plots[[i]], vp = vplayout(curRow, curCol ))
}
}
## define subplots (short example here, I specified some more aesthetics in my script)
plot1a <- qplot(variable1,variable2,data=Mydataframe1)
plot1b <- qplot(variable1,variable3,data=Mydataframe1)
plot1c <- qplot(variable1,variable2,data=Mydataframe2)
plot1d <- qplot(variable1,variable3,data=Mydataframe2)
## plot in one frame
Myplot <- multiplot(plot1a,plot1b,plot1c,plot1d, cols=2)
This gives the desired result. The problem arises when I try to save to a file. I can do this manually in RStudio (using Export -> Save plot as image), but I would like to run everything in a script. I manage to save only subplot1d (which is last_plot()), and not the complete multiplot.
What I’ve tried so far:
Using ggsave
ggsave(filename = "D:/R/plots/Myplots.jpg")
This results in only subplot 1d being saved.
Using jpeg(), print() and dev.off()
jpeg(filename = "Myplot.jpg", pointsize =12, quality = 200, bg = "white", res = NA, restoreConsole = TRUE)
print(Myplot)
dev.off()
This results in a completely white image (just the background I assume). print(Myplot) returns NULL.
Not sure what I’m doing wrong here. My lack of understanding R is the reason I am stuck trying to find a solution. Can anyone explain what I’m doing wrong and perhaps suggest a way to solve my problem(s)?
Its because Myplot is the returned value from your multiplot function, and it returns nothing (its job is to print the graphs). You need to call multiplot with the jpeg device open:
jpeg(filename = "Myplot.jpg", pointsize =12, quality = 200, bg = "white", res = NA, restoreConsole = TRUE)
multiplot(plot1a,plot1b,plot1c,plot1d, cols=2)
dev.off()
should work.
Using the example code (R cookbook), it works for me
png("chickweight.png")
multiplot(p1, p2, p3, p4, cols=2)
dev.off()
And for completeness sake, ggsave does not work as it only saves the last printed ggplot object, which in your case is just the last plot. This is caused by the fact that multiplot creates the plot by drawing the ggplot objects onto different subsets of the total graphics device. An alternative is to create the plot by combining the ggplot objects into one big ggplot object, and then printing the object. This would be compatible with ggsave. This approach is implemented by arrangeGrob in the gridExtra package.

Resources