visualizing and revising a large number of plots in for loop in r - r

Here is the question where I have a number of plots and I want to revise them one by one visually at once pace.
xm <- matrix(runif(20000), ncol = 1000)
for (i in 1:ncol(xm)){
hist(xm[,i], col = i)
}
This loop will make the plots so fast that I will have slit second to look (or not at all) in graphical device.

There can be several way around:
(1) look plots one by one - press return key to see next plot
We can create a breaks and user can use return key to see next plot.
xm <- matrix(runif(20000), ncol = 1000)
for (i in 1:ncol(xm)){
hist(xm[,i], col = i, main = paste(i))
grDevices::devAskNewPage(ask = TRUE)
}
Note that default behavior in R is grDevices::devAskNewPage(ask = FALSE).
(2) input plot number you want see from keyboard
You select which variable you want to plot, this way you can avoid chronological visualization of the plots, or else you can input the plot number(s) you want, in the order you want and click stop when you are done.
for (i in 1:ncol(xm)){
i <- scan(nmax=1)
hist(xm[,i], col = i, main = paste(i))
}
(3) all plots in new windows
If you would like to make a new plot each time, you can use:
for (i in 1:10){
hist(xm[,i], col = i, main = paste(i))
dev.new()
}
(4) multiple plot in single window
If you like to plot multiple plots in a single plot:
par(mfrow = c(5,2))
for (i in 1:10){
hist(xm[,i], col = i, main = paste(i))
}
(5) Pdf file with multiple plots in separate page
Another way to save the files as PDF or other format:
The following will create output PDF will all figures in different page and then can scrolled down up.
pdf("outtrtt.pdf",width=7,height=5)
for (i in 1:ncol(xm)){
hist(xm[,i], col = i, main = paste(i))
}
dev.off()
(6) separate pdf files per plot
Or if you want to create output as single PDF file per plot or other image file types this may do so. Please note that this may be different in mac and windows.
for (i in 1:ncol(xm)){
pdf(paste("var", i, ".pdf", sep = ""),width=7,height=5)
hist(xm[,i], col = i, main = paste(i))
dev.off()
}
(7) separate image files
You can save as jpeg or other format of your choice
for (i in 1:ncol(xm)){
jpeg(paste("var", i, ".jpeg", sep = ""),width=700,height=500)
hist(xm[,i], col = i, main = paste(i))
dev.off()
}
Other answers are welcome.

Related

plot density of multiple csv files of different size in R

I have multiple csv files, each with a single column.
I want to read them and plot their density distribution in a single plot.
can anyone help me?
There are answers elsewhere about
reading multiple csv files so I will mainly concentrate on the density plotting part. Since you did not provide any data, I will use the built-in iris data to create some example files. This first step is to make a reusable example. I am assuming that you already have the data on the disk and have a list of the file names.
## Create some test data
FileNames = paste(names(iris[,1:4]), ".csv", sep="")
for(i in 1:4) {
write.csv(iris[,i], FileNames[i], row.names=FALSE)
}
So, on to the density plots. There is one small sticky point. Each of the different density plots will cover a different range of x and y values. If you want them all in one plot, you will need to leave enough room in your plot to hold them all. The code below first computes that range, then makes the plots.
## Read in all of the data from csv
DataList = list()
for(i in seq_along(FileNames)) {
DataList[[i]] = read.csv(FileNames[i], header=T)[[1]]
}
## Find the range that we will need to include all plots
XRange = range(DataList[[1]])
YRange = c(0,0)
for(i in seq_along(DataList)) {
Rx = range(DataList[[i]])
XRange[1] = min(XRange[1], Rx[1])
XRange[2] = max(XRange[2], Rx[2])
YRange[2] = max(density(DataList[[i]], na.rm=T)$y, YRange[2])
}
## Now make all of the plots
plot(density(DataList[[1]], na.rm=T), xlim=XRange, ylim=YRange,
xlab=NA, ylab=NA, main="Density Plots")
for(i in seq_along(DataList)) {
lines(density(DataList[[i]], na.rm=T), col=i)
}
legend("topright", legend=FileNames, lty=1, col=1:4, bty='n')

Saving ggplot graphs to pdf not formatting correctly in PDF

This is a follow on question to my original here
I am currently trying to save the outputs of a ggplot graph to .pdf but I am running into some problems.
I run the following on the dput data on the original question (I repaste everything below).
library(gridExtra)
pdf("Plots.pdf", onefile = TRUE)
for(j in 1:length(plotList)) {
grid.arrange(plotList[[j]], nrow = 2)
}
dev.off()
This saves the files as a pdf document but instead of getting two graphs per page I get one graph which takes up half a page. Is it possible to resize the graphs, when I select nrow = 3 I get the same problem, I get one graph in the top 3rd / half of the page and a blank space for the rest. I provide a screen shot of the output:
Here is a minimal example:
# Make empty list for plots
plotList <- list()
# Build plots
library(ggplot2)
for(i in 1:2){
plotList[[i]] <-
ggplot(mtcars, aes(mpg, cyl)) +
geom_point() +
labs(title = i)
}
# Save plots
library(gridExtra)
pdf("Plots.pdf", onefile = TRUE)
for(j in 1:length(plotList)) {
grid.arrange(plotList[[j]], nrow = 2)
}
dev.off()
Credit to #LachlanO
You problem comes from how you are calling grid.arrange. By including it in a loop, you are telling it to create multiple separate plots, like this:
grid.arrange(plotList[[1]], nrow = 2)
grid.arrange(plotList[[2]], nrow = 2)
grid.arrange(plotList[[3]], nrow = 2)
What you actually are trying to do is create one grid.arrange object which contains all the plots. To do this, you need call the function against the list:
do.call("grid.arrange", c(plotList, nrow=2))
Alternatively, you can use the cowplot package and use:
cowplot::plot_grid(plotlist = plotList, nrow = 2)
So to save the PDF you can use:
pdf("Plots.pdf", onefile = TRUE)
do.call("grid.arrange", c(plotList, nrow=2))
dev.off()

R statistical Programing

I am trying to write R codes for the histogram plot and save each histogram separate file using the following command.
I have a data set "Dummy" and i want to plot each histogram by a column name and there will be 100 histogram plots in total...
I have the following R codes that draws the each Histogram...
library(ggplot2)
i<-1
for(i in 1:100)
{
jpeg(file="d:/R Data/hist.jpeg", sep=",")
hist(Dummy$colnames<-1, ylab= "Score",ylim=c(0,3),col=c("blue"));
dev.off()
i++
if(i>100)
break()
}
As a start, let's get your for loop into R a little better by taking out the lines trying to change i, your for loop will do that for you.
We'll also include a file= value that changes with each loop run.
for(i in 1:100)
{
jpeg(file = paste0("d:/R Data/hist", i, ".jpeg"))
hist(Dummy[[i]], ylab = "Score", ylim = c(0, 3), col = "blue")
dev.off()
}
Now we just need to decide what you want to plot. Will each plot be different? How will each plot extract the data it needs?
EDIT: I've taken a stab at what you're trying to do. Are you trying to take each of 100 columns from the Dummy dataset? If so, Dummy[[i]] should achieve that (or Dummy[,i] if Dummy is a matrix).

putting multiple plots on one pdf in r

I am outputting plots as png based on grouping according to the dataframe vector called "chr". This generates lots of plots but I would like to have them all in one png. I am using the plot function in r rather than ggplot2.
My code so far:
for(jj in ind){
png(paste("/Users/sebastianzeki/Desktop/SequencingScripts/Plots/",jj,".png"))
indic = which(ret$chr == jj)
plot(ret$binRight[indic],ret$SummedZScore[indic],pch=19,xlab="Locus",ylab="Summed ZScore",type="h",lwd=20, space=0)
dev.off()
How can I get all the plots on one png (or pdf if thats easier)?
Suppose length(ind) = 10
png(paste("/Users/sebastianzeki/Desktop/SequencingScripts/Plots/",jj,".png"))
par(mfrow=c(5,2))
for(jj in ind){
indic = which(ret$chr == jj)
plot(ret$binRight[indic],ret$SummedZScore[indic],pch=19,xlab="Locus",ylab="Summed ZScore",type="h",lwd=20, space=0)
}
dev.off()
This can make one png file or if you want to make a pdf file
How to print R graphics to multiple pages of a PDF and multiple PDFs?
Look at the above thread for help.
A simple example :
png("temp.png", width = 600, height = 2000)
par(mfrow=c(8,3), mar = rep(0.5, 4), oma = rep(0.5, 4))
for (i in 1:24) {
hist(runif(20), main = NULL)
}
dev.off()

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