Multiple plots in one figure in a loop in R - r

I am trying to save 10 plots in PNG format, but it only shows me one plot. How can I fix the code below?
par(mfrow = c(3,4))
png(filename = "roc.png", width = 1200, height = 1200)
roc = list()
for(id in 1:10)
{
roc[[id]] = ModelCross[[id]]$roc
roc_ = ModelCross[[id]]$roc
coords_<- coords(roc_, best.method="closest.topleft") ## "youden", "closest.topleft"
par(pty = "s")
plot(roc_,col = "blue",print.thres="best", print.thres.best.method="closest.topleft")
print(paste0('roc',id))
}
dev.off()

Related

Plot each sample in a new plot in R

I have quick question, I do I take these type of data and loop through and put each datapoint into a new plot?
quantity <- c(3,5,2)
names(quantity) <- c("apples","bananas", "pears")
plot(quantity)
png(file = Path, width =4, height =4, units = "in", res = 600)
par(mfrow = c(3,3)
for (i in names(quantity)){
print(i)
plot(x = quantity[i], y = names(quantity)[i])
}
dev.off()

Not able to get the proper plots in plot window. One plot missing. May someone tell why?

I am using par() function to partition the window, to accommodate three plots, but always one plot is missing. Not able to figure out why is it happening. Below is my R script function:
answer_3<-function(){
set.seed(1)
a <- runif(100)
set.seed(1)
b <- runif(100)
A<- as.data.frame(A)
B <- as.data.frame(b)
AB<-cbind(A,B)
AB_pear<-cor(x = AB,y=NULL,method = "pearson")
AB_spear<-cor(x = AB,y=NULL,method = "spearman")
AB_kend<-cor(x = AB,y=NULL,method = "kendall")
par(mfcol=c(3,1), mar=c(1,1,1,1))
#sp <-plot(AB[,1],AB[,2],main = "Plot of random uniform distribution",xlab = "uniformly distributed points_a",ylab = "uniformly distributed points_b")
library(corrplot)
Pear_p<-corrplot(corr = AB_pear,method = "circle",title = "Pearson correlogram")
Spear_p<-corrplot(corr = AB_spear,method = "circle",title = "Spearman correlogram")
Kend_p<-corrplot(corr = AB_kendall,method = "circle",title = "Kendall correlogram")
c(Pear_p,Spear_p,Kend_p)
}
The Kend_p is always missing from the plot window. What am I doing wrong?

Print multiple corrplots (R) in the figure

I am working with corrplot and following example here Plotting multiple corrplots (R) in the same graph I can display multiple corrplots(R) in the same graph. However I would like to save to a tiff file and because I working with loop I don't know how to achieve this. See code below.
I loop through several block of my experiments (Block1, block2) and plot the corrplot one next to another. This works. I don't understand how to direct to tiff file. In particular where to put
tiff(file = 'Figure4Plots.tiff', width = 12, height = 12, units = "in", res = 300) and dev.off() I tried after dflist and several others but does not work Thanks!
dflist<-c('Block1', 'Block2')
par(mfrow=c(2,2))
for (i in seq_along(dflist)) {
#Subset different Blocks
dataCorr<- subset(total , (block == dflist[i] ))
p.mat <- cor.mtest(dataCorr)
M<-cor(dataCorr)
col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
corrplot(M, method="color", col=col(200),
type="upper", title = title,
addCoef.col = "black", # Add coefficient of correlation
tl.col="red", tl.srt=45, #Text label color and rotation
# Combine with significance
p.mat = p.mat, sig.level = 0.05, insig = "blank",
diag=TRUE,
mar=c(0,0,1,0) )}
I don't have your original data, and I'm not familiar with the corrplot package, so I've made some dummy data and used just a simple plot() function. Unless there's something particular about the corrplot() function, you should be able to enclose most of your code in a tiff() block, like this:
dflist <- c('Block1', 'Block2', 'Block3', 'Block4')
total <- data.frame(block=sample(dflist, size=100, replace=TRUE), x=runif(100), y=runif(100)*2)
tiff(file = 'Figure4Plots.tiff', width = 12, height = 12, units = "cm", res = 72)
par(mfrow=c(2,2))
for (thisBlock in dflist) {
#Subset different Blocks
dataCorr <- subset(total , (block == thisBlock ))
dataCorr <- dataCorr[, c('x', 'y')]
plot(dataCorr)
}
dev.off()
This code produces Figure4Plots.tiff:

R save plots with for loop (saving histograms works)

I want to save 300 plots with a for loop but somehow the code works in the console but no plots are saved. I always get the following error:
Error in plot_list[[i]] : subscript out of bounds
If I plot histograms everything works just fine.
Here's my code:
plot_list = list()
for (i in 1:300) {
p <-plot(matrix(1:15000, nrow = 15000, ncol = 50), datamatrix[1:15000,var_list[i,1]:var_list[i,2]], main = layer_list[[1]][i], xlab = "r [micrometer]")
plot_list[[i]] = p
}
for (i in 1:300) {
png(paste("plot", i, ".png", sep = ""), width = 1200, height = 750)
plot(plot_list[[i]], main = substitute(paste('Layer ', a), list(a=layer_list[[1]][i])), xlab = "r [micrometer]", ylab = " Frequency")
dev.off()
}
If I look at the plot_list, I get:
plot_list
list()
Can anyone help? Thank you!
Please try to provide datamatrix, or at least head(datamatrix).
As in the comments, you can do this is one loop and don't need to save objects to an intermediate list.
for (i in 1:300) {
png(paste("plot", i, ".png", sep = ""), width = 1200, height = 750)
plot(matrix(1:15000, nrow = 15000, ncol = 50),
datamatrix[1:15000, var_list[i, 1]:var_list[i, 2]],
main = sprintf("Layer %s", layer_list[[1]][i]),
xlab = "r [micrometer]",
ylab = "Frequency")
dev.off()
}

Saving multiply pdf plots r

I have made a loop for making multiply plots, however i have no way of saving them, my code looks like this:
#----------------------------------------------------------------------------------------#
# RING data: Mikkel
#----------------------------------------------------------------------------------------#
# Set working directory
setwd()
#### Read data & Converting factors ####
dat <- read.table("Complete RING.txt", header =TRUE)
str(dat)
dat$Vial <- as.factor(dat$Vial)
dat$Line <- as.factor(dat$Line)
dat$Fly <- as.factor(dat$Fly)
dat$Temp <- as.factor(dat$Temp)
str(dat)
datSUM <- summaryBy(X0.5_sec+X1_sec+X1.5_sec+X2_sec+X2.5_sec+X3_sec~Vial_nr+Concentration+Sex+Line+Vial+Temp,data=dat, FUN=sum)
fl<-levels(datSUM$Line)
colors = c("#e41a1c", "#377eb8", "#4daf4a", "#984ea3")
meltet <- melt(datSUM, id=c("Concentration","Sex","Line","Vial", "Temp", "Vial_nr"))
levels(meltet$variable) <- c('0,5 sec', '1 sec', '1,5 sec', '2 sec', '2,5 sec', '3 sec')
meltet20 <- subset(meltet, Line=="20")
meltet20$variable <- as.factor(meltet20$variable)
AllConcentrations <- levels(meltet20$Concentration)
for (i in AllConcentrations) {
meltet.i <- meltet20[meltet20$Concentration ==i,]
quartz()
print(dotplot(value~variable|Temp, group=Sex, data = meltet.i ,xlab="Time", ylab="Total height pr vial [mm above buttom]", main=paste('Line 20 concentration ', meltet.i$Concentration[1]),
key = list(points = list(col = colors[1:2], pch = c(1, 2)),
text = list(c("Female", "Male")),
space = "top"), col = colors, pch =c(1, 2))) }
I have tried with the quartz.save function, but that just overwrites the files. Im using a mac if that makes any difference.
When I want to save multiple plots in a loop I tend to do something like...
for(i in AllConcentrations){
meltet.i <- meltet20[meltet20$Concentration ==i,]
pdf(paste("my_filename", i, ".pdf", sep = ""))
dotplot(value~variable|Temp, group=Sex, data = meltet.i ,xlab="Time", ylab="Total height pr vial [mm above buttom]", main=paste('Line 20 concentration ', meltet.i$Concentration[1]),
key = list(points = list(col = colors[1:2], pch = c(1, 2)),
text = list(c("Female", "Male")),
space = "top"), col = colors, pch =c(1, 2))
dev.off()
}
This will create a pdf file for every level in AllConcentrations and save it in your working directory. It will paste together my_filename, the number of the iteration i, and then .pdf together to make each file unique. Of course, you will want to adjust height and width in the pdf function.

Resources