R save plots with for loop (saving histograms works) - r

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()
}

Related

Multiple plots in one figure in a loop in 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()

Function input used as string

saving_ggplot <- function(name = 'default', plotname = last_plot()) {
image_name = paste(name, ".png", sep="")
ggsave(image_name, plot = plotname,
scale = 1,
dpi = 300, limitsize = TRUE)
}
This is my function which saves a ggplot. However, I for the life of me cannot figure out how to take the name argument as a string.
for example if someone runes saving_ggplot(FILENAME, PLOTNAME)
it will just say no object FILENAME. In python I can just capture it and use it as str(), but using as.character or toString in R still doesn't work.
Error:
saving_ggplot(weightvsageTEST, weightvsageplot)
Error in paste(name, ".png", sep = "") :
object 'weightvsageTEST' not found
Successful call using ggsave:
ggsave('weightvsage.png', plot = last_plot(),
scale = 1,
dpi = 300, limitsize = TRUE)
You can use substitute():
saving_ggplot <- function(name, plotname) {
image_name = paste0(substitute(name), ".png") # paste0 removes need for sep arg
ggsave(image_name, plot = plotname,
scale = 1,
dpi = 300, limitsize = TRUE)
}
saving_ggplot(foo, p) # saves foo.png
Alternately, if you want to stay within tidyverse quasiquotation syntax, use enexpr() instead:
enexpr(name) # instead of substitute(name)
Data:
N <- 100
df <- data.frame(x=rnorm(n=N), y=rnorm(n=N))
p <- ggplot(df, aes(x,y)) + geom_smooth()

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.

How do I embed surface plots in html documents using knitr and plotly?

I think the R Markdown (Rmd) code below should produce a html document with a surface plot embedded in it.
```{r, plotly=TRUE}
library(plotly)
py <- plotly()
x_vec = c(seq(-5, 4.9, 0.1))
x_matrix = matrix(c(x_vec), nrow = 100, ncol = 1)
y_matrix = matrix(c(x_vec), nrow = 1, ncol = 100)
data <- list(
x = x_vec,
y = x_vec,
z = matrix(c(cos(x_matrix %*% y_matrix) + sin(x_matrix %*% y_matrix)), nrow = 100, ncol = 100),
type = "surface")
layout <- list(
title = "Waaaves in r",
scene = list(bgcolor = "rgb(244, 244, 248)"))
response <- py$plotly(data, session="knitr",
kwargs = list(
layout = layout,
world_readable=FALSE,
filename = "waves example",
fileopt = "overwrite"))
```
The document creates an output with the code embdedded, but there is no plot. Just an error message saying,
"Uh oh, an error occured on the server."
Any idea what is going on here?
Instead of running py$plotly(), run py$irplot() (without the session="knitr" argument). The latter works with the py$ggplotly() method, not the py$plotly() one.

Problems saving several pdf files in R

I'm trying to save several xyplots created with a "for" loop in R and I'm not able to get complete pdf files (all files have the same size and I can't open them) if I execute the following loop:
for (i in 1:length(gases.names)) {
# Set ylim;
r_y <- round(range(ratio.cal[,i][ratio.cal[,i]<999], na.rm = T), digits = 1);
r_y <- c(r_y[1]-0.1, r_y[2]+0.1);
outputfile <- paste (path, "/cal_ratio_",gases.names[i], ".pdf", sep="");
dev.new();
xyplot(ratio.cal[,i] ~ data.GC.all$data.time, groups = data.vial, panel =
panel.superpose, xlab = "Date", ylab = gases.names[i], xaxt="n", ylim = r_y);
savePlot(filename = outputfile, type = 'pdf', device = dev.cur());
dev.off();
}
(a previous version was using trellis.device() instead of dev.new() + savePlot())
Do you know why I can't get good pdf files? If I do it "manually" it works... Any idea?
use pdf directly
for (i in seq_along(gases.names)) {
# Set ylim
r_y <- round(range(ratio.cal[,i][ratio.cal[,i]<999], na.rm = T), digits = 1)
r_y <- c(r_y[1]-0.1, r_y[2]+0.1)
outputfile <- paste (path, "/cal_ratio_",gases.names[i], ".pdf", sep="")
pdf(file = outputfile, width = 7, height = 7)
print(xyplot(ratio.cal[,i] ~ data.GC.all$data.time, groups = data.vial,
panel = panel.superpose, xlab = "Date", ylab = gases.names[i],
xaxt="n", ylim = r_y))
dev.off()
}

Resources