R baseline package saving plots in a loop - r

I'm trying to optimize the parameters for baseline in the R baseline package by changing each parameters in a loop and comparing plots to determine which parameters give me the best baseline.
I currently have the code written so that the loop produces each plot, but I'm having trouble with getting the plot saved as the class of each object I'm creating is a baseline package-specific (which I'm suspecting is the problem here).
foo <- data.frame(Date=seq.Date(as.Date("1957-01-01"), by = "day",
length.out = ncol(milk$spectra)),
Visits=milk$spectra[1,],
Old_baseline_visits=milk$spectra[1,], row.names = NULL)
foo.t <- t(foo$Visits)
#the lines above were copied from https://stackoverflow.com/questions/37346967/r-packagebaseline-application-to-sample-dataset to make a reproducible dataset
df <- expand.grid(lambda=seq(1,10,1), p=seq(0.01,0.1,0.01))
baselinediff <- list()
for(i in 1:nrow(df)){
thislambda <- df[i,]$lambda
thisp <- df[i,]$p
thisplot <- baseline(foo.t, lambda=thislambda, p=thisp, maxit=20, method='als')
print(paste0("lambda = ", thislambda))
print(paste0("p = ", thisp))
print(paste0("index = ", i))
baselinediff[[i]] <- plot(thisplot)
jpeg(file = paste(baselinediff[[i]], '.jpeg', sep = ''))
dev.off()
}
I know that I would be able to extract corrected spectra using baseline.als but I just want to save the plot images with the red baseline so that I can see how well the baselines are getting drawn. Any baseline users out there that can help?

I suggest you change your loop in the following way:
for(i in 1:nrow(df)){
thislambda <- df[i,]$lambda
thisp <- df[i,]$p
thisplot <- baseline(foo.t, lambda=thislambda, p=thisp, maxit=20, method='als')
print(paste0("lambda = ", thislambda))
print(paste0("p = ", thisp))
print(paste0("index = ", i))
baselinediff[[i]] <- thisplot
jpeg(file = paste('baseline', i, '.jpeg', sep = ''))
plot(baselinediff[[i]])
dev.off()
}
Note that this does not try to capture the already plotted element (thisplot) inside of the list. Instead, the plotting is done after you call the jpeg command. This solves your export issue. Another problem was the naming of the file. If you call baselinediff[[i]] inside of paste, you apparently end up with an error. So I switched it to a simpler name. To plot your resulting list, call:
lapply(baselinediff, plot)
If you are determined on storing the already plotted element, the capture.plotfunction from the imager package might be a good start.

Related

Weird characters appearing in the plot legend when using DoHeatmap

I was using Seurat to analyse single cell RNA-seq data and I managed to draw a heatmap plot with DoHeatmap() after clustering and marker selection, but got a bunch of random characters appearing in the legend. They are random characters as they will change every time you run the code. I was worrying over it's something related to my own dataset, so I then tried the test Seurat object 'ifnb' but still got the same issue (see the red oval in the example plot).
example plot
I also tried importing the Seurat object in R in the terminal (via readRDS) and ran the plotting function, but got the same issue there, so it's not a Rstudio thing.
Here are the codes I ran:
'''
library(Seurat)
library(SeuratData)
library(patchwork)
InstallData("ifnb")
LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
x <- NormalizeData(x)
x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})
features <- SelectIntegrationFeatures(object.list = ifnb.list)
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features)
immune.combined <- IntegrateData(anchorset = immune.anchors)
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
DefaultAssay(immune.combined) <- 'RNA'
immune_markers <- FindAllMarkers(immune.combined, latent.vars = "stim", test.use = "MAST", assay = 'RNA')
immune_markers %>%
group_by(cluster) %>%
top_n(n = 10, wt = avg_log2FC) -> top10_immune
DoHeatmap(immune.combined, slot = 'data',features = top10_immune$gene, group.by = 'stim', assay = 'RNA')
'''
Does anyone have any idea how to solve this issue other than reinstalling everything?
I have been having the same issue myself and while I have solved it by not needing the legend, I think you could use this approach and use a similar solution:
DoHeatmap(immune.combined, slot = 'data',features = top10_immune$gene, group.by = 'stim', assay = 'RNA') +
scale_color_manual(
values = my_colors,
limits = c('CTRL', 'STIM'))
Let me know if this works! It doesn't solve the source of the odd text values but it does the job! If you haven't already, I would recommend creating a forum question on the Seurat forums to see where these characters are coming from!
When I use seurat4.0, I met the same problem.
While I loaded 4.1, it disappeared

Why does creating a pdf by iteration from a list of argument fail with for/lapply?

I am relatively new to R, and it seems that, despite my loops working properly otherwise, I am unable to iterate trough a list to create pdf:
For instance this code
(Variables & libraries:)
Libraries
library(Seurat)
The different markers are lists of chain of characters like DenditicCells:
DendriticCells <- c("Kmo", "Flt3", "Ccr7", "Ccl17", "Irf8","Xcr1","Cd209")
Markers <- list(Neurons, Oligo, OPC, AstroPro, Astro, OligoPro, Pericytes, ImmuneCells, GeneOfInterest, Lymphatics, Vein, Arteries, cappilaries, Microglial, Macrophages, ThCells, Tcells, Bcells, Granulocytes, DendriticCells, CPMicrogenes, TNK, migDCs )
Markers <- setNames(Markers, c("Neurons", "Oligo", "OPC", "AstroPro", "Astro", "OligoPro", "Pericytes", "ImmuneCells", "GeneOfInterest", "Lymphatics", "Vein", "Arteries", "cappilaries", "Microglial", "Macrophages", "ThCells", "Tcells", "Bcells", "Granulocytes", "DendriticCells", "CPMicrogenes", "TNK", "migDCs" ))
Code
pdf(paste0("Run5/DotPlot6", names(Markers[x]),"Subset4.jpeg"))
DotPlot(Subset4, assay = "SCT" ,features =Markers[[x]], dot.scale = 8)
dev.off()
Works and creates a pdf, but this code:
Ret4 <- function(x){
pdf(paste0("Run5/DotPlot6", names(Markers[x]),"Subset4.jpeg"))
try(DotPlot(Subset4, assay = "SCT" ,features =Markers[[x]], dot.scale = 8))
dev.off()
}
for(i in 1:length(Markers))Ret4(i)
fails after a perfectly normal execution. I have tried variation using different format, lapply, map, and it does not work. I do not understand why this execution fails...
How can i iterate through this? In this case, Markers is a list of list of 24 elements.
Thanks a lot
Jean
solution:
Ret5 <- function(x, Markers, Subset, nameSubset){ p <- DotPlot(Subset, assay = "SCT" ,features =Markers[[x]], dot.scale = 8)
png(paste("Run5/Subset/", as.character(x),names(Markers[[x]]),".jpeg", sep = ""))
print(p)
dev.off() }
for(x in c(1:length(Markers))){ Ret5(x, Markers, Subset1, "Subset1")}

Error: Mapping must be created by 'aes()'

I am using a for loop to create 100 ggplots in R to be graphed onto one sheet of paper. However, I keep getting a mapping must be created by aes() error and I am not sure how to fix it.
I have tried the get function with and without environments, unclear where to go next.
for(i in 1:99){
nam <- paste("p", i, sep = "")
otunam <- paste("OTU", i, sep = "")
otunam1 <- get(otunam, envir = as.environment(histotu), inherits = TRUE)
plot <- ggplot(histotu, aes(x=otunam)) + geom_histogram(histotu, stat = "bin", binwidth = 0.01) + geom_vline(xintercept=expD[1,i], color = "red") + xlab(otunam)
assign(nam, plot)
}
I would like to clear this error and be able to make 100 graphs using grid.arrange. I have this part to work, but not the for loop to create the objects that it calls.

Can't store the result of pie() function R

I have a problem trying to store the result of my pie() function in a variable, it appears that it sets it to NULL whereas the plot is displayed, I don't understand why.
I want to store it in order to write it as an HTML file after.
Here is my code:
for(i in seq(1,13)){
values <- c(stat_pcs_region[ i,"pop_agriculteurs"], stat_pcs_region[i,"pop_commercant"], stat_pcs_region[i,"pop_cadres"],
stat_pcs_region[i,"pop_profIntermediaire"], stat_pcs_region[i,"pop_employes"], stat_pcs_region[i,"pop_ouvriers"],
stat_pcs_region[i,"pop_retraites"], stat_pcs_region[i,"pop_chomage"])
labels <- c("Agriculteurs", "Commercants, artisans et chef d entreprise", "Cadres", "Professions intermediares",
"Employes", "Ouvriers", "Retraites", "Chomeurs")
percentage <- round(values/sum(values)*100)
labels <- paste(percentage, "% de", labels)
p <- pie(values, labels, col = rainbow(9))
saveWidget(p, file = paste("C:/Users/henri/Downloads/Rapports_appli_geo/Pie_charts_regions/piechartPCS_reg", i, ".html", sep = ""))
}
Thanks in advance for your help

How can I combine several heatmaps using R in a signal figure

I have created 36 heatmaps with the function pheatmap, and I want to display them in just one figure. I have tried to using the function par(), but it did not work, I do not know why. Could someone tell me what should I do? Thank you very much. This is my code:
require(graphics);require(grDevices);library("pheatmap", lib.loc="D:/Program Files/R/R-3.1.1/library");library(gplots)
filenames<-list.files("D:/Project/bladder cancer/heatmap0829/heatmap/"); # detect all of the files in the fold
filename2<-strtrim(filenames,nchar(filenames)-4); # all of the filenames without extension names
par(mfrow=c(18,2)) #divide the graphics windows into a 18x2 matrix
for(i in 1:length(filename2)){
rt<-read.table(paste("D:/Project/bladder cancer/heatmap0829/heatmap/",filenames[i],sep = ""), header = T, sep = '\t') # Import the data with the ith file name
size=dim(rt) # the dimensional of the datafram
cw=400/size[1] #the width of the cell in the heatmap
rt<-log10(rt)
x <- t(data.matrix(rt))
pheatmap(x,color=greenred(256),main=filename2[i],cluster_rows = F, cluster_cols = T,cellwidth = cw, cellheight = 60,border_color =F,fontsize = 8,fontsize_col = 15)}
This is one dataset
ScaBER 5637
1 1.010001e+02
1.341186e+00 2.505067e+01
1.669456e+01 8.834190e+01
7.141351e+00 3.897474e+01
1.585592e+04 5.858210e+04
1 3.137979e+01
1.498863e+01 7.694948e+01
1.115443e+02 3.642917e+02
1.157677e+01 5.036716e+01
4.926492e+02 8.642784e+03
3.047117e+00 1.872154e+01
I have 36 txt files like this, but I can not put all of them here
"ScaBER 5637" is the column name of this dataset
See this previous answer: Histogram, error: Error in plot.new() : figure margins too large
par(mfcol=c(3,12), oma=c(1,1,0,0), mar=c(1,1,1,0), tcl=-0.1, mgp=c(0,0,0))
for(i in 1:36){
plot(runif(2), runif(2), type="l")
}
dev.off()

Resources