suppress interactive plotting in R - r

I would like to send a plot to a file using pdf(), but plot.MCMCglmm() is attempting to act interactively, which interferes with dev.off().
pdf(file="model.pdf")
plot(model, random=FALSE)
Hit <Return> to see next plot: dev.off()
And the file is not closed. Adding another dev.off() closes the file. Is there a way to suppress the interactive plotting?
EDIT example:
require(MCMCglmm)
mod_dat <- data.frame( Name = rep(letters[1:3], each=10),
Group = rep(letters[1:3], 10),
Age = rep(letters[1:5], each=6),
Happy = rep(letters[1:2], 15),
x = rnorm(30),
y = rnorm(30) )
mod_out <- MCMCglmm( y~x, random=~Name+Group+Age+Happy,
data=mod_dat, verbose=FALSE )
pdf( file="model out.pdf" )
plot(mod_out)
dev.off()
dev.off()

You could modify the plot function for plot.MCMCglmm to turn off the new page prompt. You can get the code for the function by typing plot.MCMCglmm in the console.
myPlotGLMM = function (x, random = FALSE, ...)
{
nF <- x$Fixed$nfl
#devAskNewPage.orig <- devAskNewPage()
if (random) {
nF <- sum(rep(x$Random$nrl, x$Random$nfl)) + nF
if (nF != dim(x$Sol)[2]) {
stop("random effects not saved and cannot be plotted")
}
}
plot(x$Sol[, 1:nF, drop = FALSE], ...)
#devAskNewPage(TRUE)
if (is.null(x$Lambda) == FALSE) {
plot(x$Lambda, ...)
#devAskNewPage(TRUE)
}
plot(x$VCV, ...)
#devAskNewPage(devAskNewPage.orig)
}
myPlotGLMM(model)

Another option is to plot everything onto one page. Without a reproducible example I can't test this but this should work:
pdf(file="model.pdf")
par(mfrow=c(2,2))
plot(model, random=FALSE)
dev.off()
So if this generated four plots, they would be arranged on one page in 2 x2 grid.

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

biwavelet package: "axis" is not working

I am using biwavelet package to conduct wavelet coherence analysis. When I want to set my own x ticklabel, I find axisis not working. The following gives a reproducible example. Thanks.
require(biwavelet)
t1 <- cbind(1:100, rnorm(100))
t2 <- cbind(1:100, rnorm(100))
wtc.t1t2 <- wtc(t1,t2,nrands = 10)
plot(wtc.t1t2, plot.cb = TRUE, plot.phase = TRUE,xaxt='n')
axis(1,at = seq(10,100,10),labels = seq(1,10,1))
The thing that was breaking your plot was plot.cb = TRUE.
In the source code for plot.biwavelet the author notes the following about the plot.cb option:
## Add color bar: this must happen after everything, otherwise chaos
ensues!
So that was the problem -- you invoked axis() after plot.cb and chaos ensued. However, you can manually add back the color bar using image.plot from the fields package, after having run plot without plot.cb then having added your axis().
pacman::p_load(biwavelet,fields)
t1 <- cbind(1:100, rnorm(100))
t2 <- cbind(1:100, rnorm(100))
wtc.t1t2 <- wtc(t1,t2,nrands = 10)
plot(wtc.t1t2, plot.phase = TRUE,xaxt='n')
axis(1,at = seq(10,100,10),labels = seq(1,20,2))
image.plot( zlim=c(0,25), legend.only=TRUE)
You can customize the ticks and the color bar to your liking this way!

Adding axis titles in gplot using filled.contour in R

This is my reproducible code example. Everything looks as it should in the graph, except the axis titles/labels are not being added. I am really struggling to figure out how to fix it, despite following the directions in the function documentation. Help will be much appreciated - thanks in advance.
output <- matrix(data = c(0.7,0.5,0.3,0.8,0.6,0.4,0.9,0.7,0.5,1,0.8,0.6),nrow=3,
ncol=4)
# Change column names
colnames(output) <- c(10,20,30,40)
# Change row names
rownames(output) <- c(1,2,3)
library(gplots)
matrix.axes <- function(data) {
# Do the rows, las=2 for text perpendicular to the axis
x <- (1:dim(data)[1] - 1) / (dim(data)[1] - 1);
axis(side=1, at=x, labels=rownames(data), las=1);
# Do the columns
x <- (1:dim(data)[2] - 1) / (dim(data)[2] - 1);
axis(side=2, at=x, labels=colnames(data), las=2);
}
# Not necessary to save as pdf unless this is part of the problem
# save to pdf
# pdf("C:/Test.pdf")
# Plot results
filled.contour(output,plot.title=title(main="Method"),
xlab='Case number',ylab='Sample number',
plot.axes=matrix.axes(output))
# dev.off()
Your xlab = and ylab = need to be inside the plot.title() function:
filled.contour(output,
plot.title = title(main = "Method", xlab='Case number', ylab='Sample number'),
plot.axes = matrix.axes(output))

Reset graph at the end of the loop :could not find function "device" error

I am trying to generate plots by looping, here is my code:
n <- unique(wide_data$Product.Code)[1:3]
for (i in n)
{
my.prod2 <- filter(tall_bind, Product.Code == i, Date > ymd("2012/04/01"))
dev.new()
mypath <- file.path("C:","R","SAVEHERE",paste("myplot_", i, ".jpg", sep = ""))
jpeg(file=mypath)
mytitle = paste("Plot for product", i)
p <- qplot(Date, Sold, data = my.prod2, geom = "line", main=mytitle, group = Model, colour = Model) + facet_grid(Model ~ .)
ggsave("myplot_", i, plot=p, device= "jpg" )
}
I get the following error for the above code:
Saving 6.67 x 6.67 in image
Error in ggsave("myplot_", i, plot = p, device = "jpg") : could
not find function "device"
Earlier when I used dev.off() at the end of the loop, I found that though the graphs were being generated they were totally blank.
Could someone please help me understand where is the mistake in my code?
You can leave out the dev.new() and jpg() commands, and also your arguments to ggsave() are incorrect. This should work:
n <- unique(wide_data$Product.Code)[1:3]
for (i in n) {
my.prod2 <- filter(tall_bind, Product.Code == i, Date > ymd("2012/04/01"))
mypath <- file.path("C:","R","SAVEHERE",paste("myplot_", i, ".jpg", sep = ""))
mytitle = paste("Plot for product", i)
p <- qplot(Date, Sold, data = my.prod2, geom = "line", main=mytitle, group = Model, colour = Model) + facet_grid(Model ~ .)
ggsave(filename = mypath, plot = p)
}
What you did was creating a new default graphics device, typically a plotting window, then a jpeg graphics device, i.e. a file. Then you tried to make ggplot2 to plot to directly to file using ggsave, i.e. using its own (jpg) device, and not using either of the two graphics devices you created.
The error, however, was because you gave ggsave the wrong arguments. But even with the right arguments, you would still have ended up with additional unused graphics windows and files through the dev.new() and jpeg() commands. I suggest some extra reading of the help (e.g. type ?ggsave at the r console).
Typically, when using ggplot2 you do not need to worry about dev.new, jpeg and the like. qplot or ggplot and ggsave should do all you need.

Making simple R GUI with tcltk package

I'm trying to make very simple GUI for my script. In nutshell problem looks like that :
dataset is dataframe, I would like to plot one column as the time and use simple GUI for choosing next/previus column.
dataset <-data.frame(rnorm(10), rnorm(10), rnorm(10))
columnPlot <- function(dataset, i){
plot(dataset[, i])
}
how to use tcltk for calling fplot with different i's ?
Not what you asked for (not tcltkrelated), but I would advise you to have a look at the new shiny package from RStudio.
Are you particularly attached to the idea of using tcltk? I've been working on something similar using the gWidgets package and have had some success. According to it's CRAN site, "gWidgets provides a toolkit-independent API for building interactive GUIs". This package uses tcltk or GTK2 and I've been using the GTK2 portion. Here's a quick example of a GUI with a spinbutton for changing i. I also added a little fanciness to your function because you mentioned you would be plotting time series, so I made the x axis Time.
data<-data.frame(rnorm(11),rnorm(11),rnorm(11))
i = 1
fplot <- function(i, data = data){
library(ggplot2)
TimeStart <- as.Date('1/1/2012', format = '%m/%d/%Y')
plotdat <- data.frame(Value = data[ ,i], Time = seq(TimeStart,TimeStart + nrow(data) - 1, by = 1))
myplot <- ggplot(plotdat, aes(x = Time, y = Value))+
geom_line()
print(myplot)
}
library(gWidgets)
options(guiToolkit = 'RGtk2')
window <- gwindow ("Time Series Plots", visible = T)
notebook <- gnotebook (cont = window)
group1 <- ggroup(cont = notebook, label = "Choose i", horizontal=F)
ichooser <- gspinbutton(cont = group1, from = 1, to = ncol(data), by = 1, value = i, handler = function(h,...){
i <<- svalue(h$obj)})
plotbutton <- gbutton('Plot', cont = group1, handler=function(h,...){
fplot(i, data)})
graphicspane1 <- ggraphics(cont = group1)

Resources