Task Schedular Giving Error while scheduling R Script for saving PDF - r

I am scheduling R script which contains ggsave for saving pdf.
my code is running but on the line of ggsave("plot.pdf), it is skipping code. But instead of saving pdf if i use png format then it is fine. but only for pdf it is giving problem.
Below is my sample code.
library(ggplot2)
library(data.table)
a <- data.frame(a = c(1:5))
p <- ggplot(data.frame(x = 1:5, y = 1:5), aes(x, y)) + geom_point()
fwrite(a,"abc1.csv")
ggsave("plot.pdf")

Does ggsave(p, "plot.pdf", device = "pdf") work? You may not have been specifying the plot to be saved or perhaps it doesn't know to export as pdf from only the file path that you gave?
EDIT: It should be ggsave("plot.pdf", p, device = "pdf") so that the arguments are in the correct order.

Related

ggplot2 does not show the graph in Latex (knitr)

I have an issue with knitr and ggplot2 in Latex. I am trying to create a dynamic document with knitr. All my plots are in ggplot2. Hear me out:
I created the Latex document
I opened it in R Studio and saved the TEX file as RNW file. Global and Project options: knitr.
I pasted the R script there like:
<<echo=FALSE>>=
knitr::opts_chunk$set(fig.path='graphs/',
echo=FALSE, warning=FALSE, message=FALSE)
#
<<>>=
library(ggplot2)
library(tidyverse)
#
<<plot1>>=
my_data1 <- read.csv(file.choose(), header=TRUE, sep=",")
plot1 <- ggplot(data=my_data1, aes(x = pos , y = sum)) +
geom_line(colour = 'black', size = 1) +
scale_y_continuous(trans = 'log10', limits = c(1,100)) +
theme_classic() +
labs (x = 'axis_name1', y = 'axis_name2') +
coord_cartesian(xlim = c(1219890,1220102)) +
#
Everything is going well, except the graph does not show when I press 'Compile PDF' or in the graphs directory. However when I select only the R code and run it everything is fine(as long as I add print()). I managed to use TikZ which works just fine but without creating a dynamic document. I thought it was possible to output the plot directly in the PDF document but for some reason ggplot2 does not work. Is there something that I am missing?
Thank you.

Save and Load a ggplot plot

I am working on a large shinydashboard and was keeping my code for modeling in a separate file from the main app.R. The problem is that I need to plot my data. This requires that I save my ggplots from one file and load them in my main app.R file. How can I save my ggplots and load them.
As a simple example lets say I have the following
#make plot
> p <- mtcars %>%
ggplot(aes(x = mpg, y = cyl))+geom_point()
#save plot
> save(file=here::here("plots/a_plot.Rdata"),p)
#load plot
> p <- load(file=here::here("plots/trans_arima.Rdata"))
> p
[1] "p"
How can I load my ggplot?
You can save your plot as a png file and then load it back into youyr file
you have several option for saving your plot. you could use ggplot2s' ggsave()
function or you could use the save_plot() from the cowplot package. save_plot() is said to
give you more flexibility when it comes file adjusting hence my pick.
You can explore both.
refer to https://rdrr.io/cran/cowplot/man/save_plot.html to read more about save_plot.
tmp = data.frame(first = c('a','b','c','d','e','f','g','h','i','j','k','l','m','n'),
second = c(2,3,4,5,2,3,4,5,6,3,4,4,6, 7))
plot_tmp = ggplot(tmp, aes(first, second)) + geom_bar(stat = 'identity')
dev.new()
if("png" %in% installed.packages()){
library(png)
}else{
install.packages("png")
library(png)
}
save_plot("~/plot_tmp.png", plot_tmp, base_height = NULL, base_aspect_ratio = 1.618,
base_width = 6)
Use the following steps to load files into your shiny using by using the
#read plot
library(OpenImageR)
img<-OpenImageR::readImage("~/plot_tmp.png")
imageShow(img)
Hopefully this helps. To read more about OpenImageR and how you can use it in shiny please go to https://cran.r-project.org/web/packages/OpenImageR/vignettes/The_OpenImageR_package.html
have fun!!!

tikz produces empty file in R loop

I am using the tikzDevice library in R to produce tikzpicture plots in latex. It works when plots are produced one by one. However, when I want to produce the plots in a loop, I get empty files. This issue is illustrated in the following minimal example:
library(ggplot2)
library(tikzDevice)
df <- data.frame(
x = c(1, 2),
y = c(1, 2)
)
path <- 'some path here'
for (j in 1:25){
filename <- paste(path, j, sep = '')
filename <- paste(filename, '.tex', sep = '')
tikz(file = filename)
plot <-
ggplot(data=df, aes(x=x, y=y))
plot
dev.off()
}
This produces 25 empty plots. However, if I run the code without the for loop (for instance, copying the content in the loop 25 times and changing j accordingly, then it produces the plots. What is the problem here?
plot(plot) or one loses the plot

Unknown graphics device error in Rstudio

I want to save 10 different ggplots to disc with different parameters, but getting the error:
Error: Unknown graphics device ''
Here is my code:
for (geneNum in 1:10) {
geneCounts <- plotCounts(dds, gene=gene_list[geneNum],
intgroup=c("Groups","Mouse"), returnData=TRUE)
ggplot(geneCounts, aes(x=Mouse, y=count, color=Groups,
group=Groups)) +
scale_y_log10() + geom_point(size=3) + geom_line() +
ggtitle(gene_list[geneNum])
filename <- paste0("gene", geneNum, sep="_")
ggsave(filename,
plot = last_plot(), # or give ggplot object name as in myPlot,
width = 5, height = 5,
units = "in", # other options c("in", "cm", "mm"),
dpi = 300)
}
Any suggestions would be greatly appreciated.
(Copied from Alistaire's comment.)
ggsave() looks for the file extension on the filename, e.g. .png, and uses the appropriate (what R calls) graphics device to save the image (really, the kind of system used to encode the image data, PNG, BMP, JPG, PDF etc.). This error is usually caused by a missing or incorrect file extension in the filename. Specifically, in your case,
change
filename <- paste0("gene", geneNum, sep="_")
to e.g. (for .png output):
filename <- paste0("gene", geneNum, ".png", sep="_")

Unable to generate PDF with neural network graph

I'm trying to create a hard-copy image of a neural network graph and it keeps failing. If I try to create a PNG, nothing is generated, and if I try to generate a PDF I get a small file output that refuses to open with "file may be damaged" errors. If I just let it display in a graphics window, the image comes up fine.
I'm using 2.15.1 on OS X (10.7.4), built by Macports. The code I'm working with at the moment:
library(ALL)
library(neuralnet)
data(ALL)
ALL.pdat <- pData(ALL)
bt <- factor(substring(ALL.pdat$BT,1,1))
all.sds <- apply(exprs(ALL),1,sd)
top.10.sds <- rank(all.sds)>length(all.sds)-10
exprs.top.10 <- as.data.frame(t(exprs(ALL)[top.10.sds,]))
nn.data <- cbind(exprs.top.10, as.numeric(bt))
## Gene names start with a number, and that causes problems when trying to set up the
## formula for neuralnet.
col.names <- paste("g", colnames(nn.data), sep = '')
col.names[11] <- "bt"
colnames(nn.data) <- col.names
my.nn <- neuralnet(bt ~ g36108_at + g36638_at + g37006_at + g38096_f_at + g38319_at + g38355_at + g38514_at + g38585_at + g39318_at + g41214_at, nn.data, hidden = 10, threshold = 0.01)
summary(my.nn)
pdf("./nn-all.pdf")
plot.nn(my.nn)
dev.off()
png("./nn-all.png")
plot.nn(my.nn)
dev.off()
I've even rebooted the machine to make sure that all the memory is cleared up, and that didn't help any.
Simple reproducible example:
pdf("test.pdf")
set.seed(42)
plot(runif(20),rnorm(20))
png("test.png")
set.seed(42)
plot(runif(20),rnorm(20))
dev.off()
If I try to open the PDF with Adobe Reader on my German Windows 7, I get a nice informative error message telling me that the file cannot be opened because the file is in use by another application. This can be fixed easily:
pdf("test.pdf")
set.seed(42)
plot(runif(20),rnorm(20))
dev.off() #make sure to close the graphics device
png("test.png")
set.seed(42)
plot(runif(20),rnorm(20))
dev.off()
Edit:
The problem is plot.nn. Until the package gets patched, you need to redefine plot.nn manually as shown in this answer.

Resources