Using a for loop to save multiple ggplot as jpeg - r

I'd like to save multiple ggplots as jpegs through a for loop. But when I've tried to adapt code I've written for a basic plot command, I get no output (nothing is saved to my working directory).
For Example, this works great:
library(cowplot)
library(ggplot)
X<-c(1,2,3,4,5,6,7,8,9)
Y1<-c(2,3,4,4,3,2,4,5,6)
Y2<-c(3,4,5,3,2,1,1,2,3)
Y3<-c(4,5,6,7,8,9,8,7,6)
DF<-data.frame(X,Y1,Y2,Y3)
for(i in 1:3){
jpeg(paste(i,".jpeg",sep=""))
plot(DF[,1],DF[,i+1])
dev.off()
}
I end up getting three jpeg files saved to my working directory.
I'm not sure how to properly index the ggplot call here for i, but even this should return 3 instances of the same plot:
for(i in 1:3){
jpeg(paste(i,".jpeg",sep=""))
ggplot(data=DF,aes(x=X,y=Y1))+geom_line()
dev.off()
}
In the end, I was hoping to combine multiple plots onto one jpeg, and then save multiple jpegs like this:
for(i in 1:3){
jpeg(paste(i,".jpeg",sep=""))
A<-ggplot(data=DF,aes(x=X,y=Y1))+geom_line()
B<-ggplot(data=DF,aes(x=X,y=Y2))+geom_line()
C<-ggplot(data=DF,aes(x=X,y=Y3))+geom_line()
plot_grid(A,B,C)
dev.off()
}
So this plot should also return 3 instances of the same plot, all with different indexed file names. But again, I get nothing.
So my question is why is there a difference between generic plotting and ggploting in this for loop. And how can one save mutliple jpegs from ggplots like above?

How about
library(gridExtra) # gridExtra::arrangeGrob
for(i in 1:3) {
jpeg(paste0(i, ".jpg"))
A <- ggplot(data = DF, aes(x = X, y = Y1)) + geom_line()
B <- ggplot(data = DF, aes(x = X, y = Y2)) + geom_line()
C <- ggplot(data = DF, aes(x = X, y = Y3)) + geom_line()
grid.arrange(arrangeGrob(A, B, C, ncol = 3))
dev.off()
}
Note: this solution does not produce the side annotations of cowplot ("A", "B", "C").

using your code:
for(i in 1:3){
jpeg(paste(i,".jpeg",sep=""))
A<-ggplot(data=DF,aes(x=X,y=Y1))+geom_line()
B<-ggplot(data=DF,aes(x=X,y=Y2))+geom_line()
C<-ggplot(data=DF,aes(x=X,y=Y3))+geom_line()
k<-plot_grid(A,B,C)
ggsave(k, filname = "path/finalplot.jpeg")
}
look at ?ggsave to look at other arguments to specify like height and width

Related

drawing multiple plots, 2 per page using ggplot

I have a list of dataframes and I would like to print them all in a .RMarkdown document with 2 per page. However, I have not been able to find a source for doing this. Is it possible to do this via a for loop?
What I would like to achieve is something with the following idea:
listOfDataframes <- list(df1, df2, df3, ..., dfn)
for(i in 1:){
plot <- ggplot(listOfDataframes[i], aes(x = aData, y = bData)) + geom_point(color = "steelblue", shape = 19)
#if two plots have been ploted break to a new page.
}
Is this possible to achieve with ggplot in rmarkdown? I need to print out a PDF document.
If you just need to output plots with two per page, then I would use gridExtra as was suggested above. You could do something like this if you were to put your ggplot objects into a list.
library(ggplot2)
library(shinipsum) # Just used to create random ggplot objects.
library(purrr)
library(gridExtra)
# Create some random ggplot objects.
ggplot_objects <- list(random_ggplot("line"), random_ggplot("line"))
# Create a list of names for the plots.
ggplot_objects_names <- c("This is Graph 1", "This is Graph 2")
# Use map2 to pass the ggplot objects and the list of names to the the plot titles, so that you can change them.
ggplot_objects_new <-
purrr::map2(
.x = ggplot_objects,
.y = ggplot_objects_names,
.f = function(x, y) {
x + ggtitle(y)
}
)
# Arrange each ggplot object to be 2 per page. Use marrangeGrob so that you can save two ggplot objects per page.
ggplot_arranged <-
gridExtra::marrangeGrob(ggplot_objects_new, nrow = 2, ncol = 1)
# Save as one pdf. Use scale here in order for the multi-plots to fit on each page.
ggsave("ggplot_arranged.pdf",
ggplot_arranged, scale = 1.5)
If you have a list of dataframes that you are wanting to create ggplots for, then you can use purrr::map to do that. You could do something like this:
purrr::map(df_list, function(x) {
ggplot(data = x, aes(x = aData, y = bData)) +
geom_point(color = "steelblue", shape = 19)
})

Export and re-import ggplot object

I have two different (very long) R scripts, each ultimately producing two ggplots (p and q).
I want to save these two plots as "gg-files", so that I can re-upload them in a third R script, where I will use ggarrange (or else) to merge them for an academic publication.
How can I export/import ggplots as "gg-objects"?
My apologies for my code - I'm a newbie
Thank you in advance!
I have looked into several methods of saving (e.g. ggsave, svg() def.off(), imager package, rsvg package) but none provided what I am looking for.
# script A
rm(list = ls()) # clean environment
dat <- data.frame(x = 1:10, y = 1:10)
p <- ggplot(dat, aes(x = x, y = y)) + geom_point()
svg(filename = "p.svg") # saves as image
p
dev.off()
# script B
rm(list = ls()) # clean environment
dat <- data.frame(x = 1:10, y = 1:10)
q <- ggplot(dat, aes(x = x, y = y)) + geom_point()
# script C
rm(list = ls()) # clean environment
## import images - how?
## combine
ggarrange(
p, q,
nrow = 2
)
You can save them like this:
xx <- ggplot(mtcars)+geom_histogram(aes(x=cyl))
save(xx, file = "G:/gpl.rdata")
Then load them :
load("G:/gpl.rdata")
This will bring the whole object in and you can see the data used to build the plot and other features of the plot

How to create a matrix of plots with R and ggplot2

I am trying to arrange n consecutive plots into one single matrix of plots. I get the plots in first place by running a for-loop, but I can't figure out how to arrange those into a 'plot of plots'. I have used par(mfrow=c(num.row,num.col)) but it does not work. Also multiplot(plotlist = p, cols = 4) and plot_grid(plotlist = p)
#import dataset
Survey<-read_excel('datasets/Survey_Key_and_Complete_Responses_excel.xlsx',
sheet = 2)
#Investigate how the dataset looks like
glimpse(Survey)#library dplyr
#change data types
Survey$brand <- as.factor(Survey$brand)
Survey$zipcode <- as.factor(Survey$zipcode)
Survey$elevel <- as.factor(Survey$elevel)
Survey$car <- as.numeric(Survey$car)
#Relation brand-variables
p = list()
for(i in 1:ncol(Survey)) {
if ((names(Survey[i])) == "brand"){
p[[i]]<-ggplot(Survey, aes(x = brand)) + geom_bar() +
labs(x="Brand")
} else if (is.numeric(Survey[[i]]) == "TRUE"){
p[[i]]<-ggplot(Survey, aes(x = Survey[[i]], fill=brand)) + geom_histogram() +
labs(x=colnames(Survey[i]))
} else {
p[[i]]<-ggplot(Survey, aes(x = Survey[[i]], fill = brand)) + geom_bar() +
labs(x=colnames(Survey[i]))
}
}
I think plots are appended correctly to the list but I can not plot them in a matrix form.
The problem does not appear to be with your multiple plots, but how you are calling the variable into your plot.
You've already put "Survey" into ggplot as the first argument (the data slot). In the mapping argument (the second slot), you put in aes(...) and inside that you should be specifying variable names, not data itself. So try this:
Where you have aes(x = Survey[[i]], fill=brand)) in two places,
put aes(x = names(Survey[[i]], fill=brand)) instead.
Regarding plotting multiple plots, par(mfrow... is for base R plots and cannot be used for ggplots. grid.arrange, multiplot, and plot_grid should all work once you fix the error in your plot.

Storing do.call("grid.arrange") output without printing

I would like to create a variable p that contains a plot with four ggplot2 subplots. I am able to achieve this with the below code:
library(ggplot2)
library(gridExtra)
data = diamonds[1:50,]
x = data$x
myPlots = lapply(c(1,5,6,7), function(i){
y = as.data.frame(data[,i])
y = y[,1]
df = data.frame(x=x,y=y)
p <- qplot(x, y, data=df)
p
})
p = do.call("grid.arrange", c(myPlots, ncol=2))
I like that I can use the variable p later by calling:
library(grid)
grid.draw(p)
However, I do not like that when I initially create p with the do.call("grid.arrange") syntax, it plots it automatically (at least in RStudio).
My question is: Is it possible to create p to be stored for later use, without plotting it upon its creation?

Multiple ggplot objects in list is altered in loop

I am saving multiple ggplots to a list to be used in a subsequent multiplot. The plots are generated in a loop and appended to the list, however, after the loop all plot objects in the list are the same as the last plot of the loop. I have done the type of operation before, without any issues. Has anyone experienced the same, and solved the problem?
figList <- list()
aoinum <- 1
for (aoi in AOI_list){
...
# prepare dataframe for plotting
dat <- data.frame(...)
fig <- ggplot(data=dat, aes(x=x, y=y, fill=z, alpha=q)) +
geom_bar(...)+
...
figList[[aoi]] <- fig
aoinum = aoinum + 1
}
This is how I managed to make a list of plots in a for loop
#Define list
ggcluster<-list()
for (cluster in 1:nclusters){
# Simple plot )geom_polygon in my case)
ggcluster[[cluster]]<-ggplot() +
geom_polygon(data = datoshp.df, aes(long, lat, group = group))
}
# Build multiplot panel (two columns)
pngname<-paste(output_path,"plot-name",".png",sep="")
png(pngname,width = 1000, height = 1000)
do.call(grid.arrange, c(ggcluster,list(ncol=2)))
dev.off()

Categories

Resources