error in rmarkdown when plotting - r

I am new to this forum and new to R in general.
But recently I was introduced to rmarkdowns in Rstudio and I have been getting a script ready that uses some csv files to run some calculations and then creates some plots.
Scrip as follows (data attached):SE_MACover_Abr2014_40m_CP.csv
```{r prepare the data}
df <- read.csv(file.choose()) #SE_MACover_Abr2014_40m_CP.csv
# call the libraries
library(ggplot2)
library(plyr)
library(reshape2)
str(df)
df
## create factor levels
df$Stat <-factor(df$Stat, levels = c("SE_Mean", "SE_Min","SE_Max"))
df$Imgs <- factor(df$Imgs, levels = c("2", "5","10", "20","30", "40", "50", "60", "70"))
df$Stat
df$Imgs
```{r plot means, mins, and maxs}
Plot1 <- ggplot(data = df, aes(x = Imgs, y = X, group = Stat)) +
geom_line(aes(linetype = Stat, colour = Stat), size = 1) +
geom_point(aes(colour=Stat)) +
ylab(bquote('Standard Error ')) +
xlab(bquote('Number of Images'))
Plot1
I tried this in R base and worked fine, but rmarkdown in Rstudio the plots do not plot and it gives me the following error message:
Error in (function (filename = "Rplot%03d.png", width = 480, height = 480, : invalid 'filename'
looking at the traceback it shows the following:
stop("invalid 'filename'")
(function (filename = "Rplot%03d.png", width = 480, height = 480, units = "px", pointsize = 12, bg = "white", res = NA, family = "sans", restoreConsole = TRUE, type = c("windows", "cairo", "cairo-png"), antialias = c("default", "none", "cleartype", "gray", "subpixel")) ...
do.call(what = png, args = args)
.rs.createNotebookGraphicsDevice(filename, height, width, units, pixelRatio, extraArgs)
(function () { .rs.createNotebookGraphicsDevice(filename, height, width, units, pixelRatio, extraArgs) ...
grid.newpage()
print.ggplot(x)
function (x, ...) UseMethod("print")(x)
I even tryied plotting the simplest graph with this code:
x <- c(1,2,3,4,5,6)
y <- c(1,2,3,4,5,6)
plot(x,y)
While I was trying to work this out as I thought there was a problem with my script,
someone suggested to paste the piece of script for plotting straight into the console.
I did so and it worked!
And it produces the same error in rmarkdown, but it runs fine in the console..
I don't know how to fix this so I can run my markdown file and it will create the graphs I need,
Please help me

This issue often arises when temporary paths plus filenames created by RStudio when generating the rmarkdown document are too long. On Windows systems, this is generally 260 characters long, but the exact length depends on whether your disk is formatted using FAT, NTFS, etc. Note that the problem is temporary files created by RStudio--you generally can't control these.
However, you can control the length of the path of your rmarkdown documengt. If it is short enough, it will leave "space" for RStudio to create the temporary file name.
Alternatively, restarting RStudio often works, although when working on the rmarkdown document, if you run into the problem again you'll have to restart again.

I had the same issue and I just realized this was due to the filename of my Rmd file--I used a % in the name. The issue disappeared after removing the symbol. What's the filename of your Rmd file? Maybe you should try to rename your file.

Related

How to reduce the size of a plot in Jupyter Notebook?

I'm trying out R with Jupyter Notebook and for some reason the plots are huge. How can I reduce the size of the plot? I tried changing the plot_scale option via: options(jupyter.plot_scale=.25) but nothing happened. I've tried other numbers besides .25, but it has no effect.
I also tried
options(repr.plot.width = 1, repr.plot.height = 0.75, repr.plot.res = 100)
as well as options(jupyter.plot_mimetypes = c("text/plain", "image/png" )), but both gave the following error:
Error in value[[3L]](cond): invalid graphics state
Traceback:
plot without title
Ideally, I'm looking for a global solution (i.e. one that changes the default plot size, rather than having to individually scale each plot). Any suggestions?
Try the following:
options(repr.plot.width = 5, repr.plot.height = 5)
x = seq(0,2*pi, length = 50)
y = sin(x)
plot(x,y)
Then compare it to the output from the following in another cell or after restarting the kernel:
options(repr.plot.width = 15, repr.plot.height = 15)
x = seq(0,2*pi, length = 50)
y = sin(x)
plot(x,y)
You should see a difference.
If you set the width and height to you get plot without title error.
Should be good with 2 or above because ~1.8 or above worked in my tests.
Based on this post.
simply run
dev.off()
then rerun your code for plotting.
Alternativly use ggplot. If the error persists you should still try dev.off() and rerun your code.
Otherwise you still have the option to restart your notebook or reinstall R.

Task Schedular Giving Error while scheduling R Script for saving PDF

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.

Plotly - unused arguments error - appears inconsistent

I am creating a Rmarkdown document that contains a number of plots created with plotly.
I cannot figure out why one of my plots is throwing an 'unused arguments' error, as the plot I create before it, which using the same arguments but a different subset of data, works fine. I want to use these 2 plots in a subplot.
Here's what I've got:
df_subset1_p <-
plot_ly(df_subset1, x = ~Month, y = ~data.percent, width = 800, height = 500) %>%
add_lines(color = ~cat) %>%
layout(xaxis = x, yaxis = y, margin = m)
df_subset2_p <-
plotly(df_subset2, x = ~Month, y = ~data.percent, width = 800, height = 500) %>%
add_lines(color = ~cat) %>%
layout(xaxis = x, yaxis = y, margin = m)
Before I can even call the subplot, df_subset2_p throws the error:
Error in plotly(df_subset2, x = ~Month, y = ~data.percent, : unused arguments (x = ~Month, y = ~data.percent, width = 800, height = 500)
I get the error on the 2nd plot, even if I try to run it first. The error reproduces if I just run the script and not the RMarkdown.
The structure of the dataframes looks fine to me. Month is a factor and data.percent is numeric for both.
I tried removing width, height and layout options, same error.
The error reproduces if I run the script without Rmarkdown.
I haven't found this exact problem reported by others on SO, though there are some similar complaints suggesting a compatibility issue between plotly and ggplot (older versions) or that another loaded package is using the same function name. But I don't see how this can be the case here, since I have many previous plots in the notebook that work fine.
df_subset2_p <-
plotly([...])
should be:
df_subset2_p <-
plot_ly([...])
Edit:
See ?plotly and ?plot_ly
The error was all in the typo. (Sighs.)
plot_ly initiates a plotly visualization, whereas plotly is a deprecated function previously used to store plotly account credentials.
Always use plot_ly.

Copy R plot to clipboard with custom size

Is there a way to get R / RStudio to copy a plot to the clipboard with a custom size?
RStudio has this function, but you have to define the size everytime and there is some extra clicking which I am sure is avoidable.
I tried my best with saving as jpeg or else with file="clipboard" and then - after plotting - dev.off(). No error messages, but also nothing in the clipboard.
Here is an example:
data(mtcars)
jpeg(file = "clipboard",width = 800, height = 600, units = "px", pointsize = 12,
quality = 100,
bg = "white", res = NA, family = "", restoreConsole = T)
hist(mtcars$mpg)
dev.off()
Any ideas on how this can be achieved?
The best way would be to be able to control the size in Rstudio, but as you have found out yourself from the Rstudio-website, Rstudio doesn't support that. The following code saves your plot to wmf. There is also a workaround to a save to bitmap, which involves some clicking, but at least you don't have to specify the size any more:
data(mtcars)
windows(800, 600, pointsize = 12) #opens a separate window with the size you want
hist(mtcars$mpg) #draw to this (active) window
savePlot("clipboard", type="wmf") #saves plot to WMF
Unfortunately, it seems to be impossible to save to jpg format to the clipboard. You can copy it to a bitmap by going to this window, click CTRL-C and the graph is on the clipboard as bitmap with 800:600.
EDIT:
The windows command only works on Windows.
For Mac, it should be replaced by: quartz(width=8,height=6,pointsize=12,dpi=100) (width/height in inches!)
For linux try x11(width=8,height=6,pointsize=12,dpi=100) (untested).
I know this is an old post, but recently looking to do the same I came across this Gist which worked well:
https://gist.github.com/dpashouwer/4223903d3ed5783158b7e63992155649
library(tidyverse)
gg_to_clipboard <- function(plot = last_plot(), width = 1000, height = 600, pointsize = 40){
win.graph(width = width, height = height, pointsize = pointsize)
plot %>% print()
savePlot("clipboard", type = "wmf")
dev.off()
}
ggplot(data = mtcars, aes(x = mpg)) + geom_histogram()
gg_to_clipboard()
Making the function makes it very simple.
With Windows and RStudio, you click Export, click Copy Plot to Clipboard, and Copy Plot.
Then, paste into Word or PowerPoint or whatever.
No need to change sizes unless you want to.
This is not command line, but hardly seems onerous.

How do I prevent Rplots.pdf from being generated?

I am working with some R code that generates a number of images as png files; however, a Rplots.pdf file keeps on being generated in the working directory, is there a way to prevent this from happening?
library(Cairo)
CairoPNG(file = "graphs.png")
nf <- layout(matrix(c(1:8), 2, 4, byrow=T), c(1, 1), c(1, 1, 1, 1), TRUE)
for (k in 1:num.k) {
plotMatrix(connect.matrix.ordered[k,,], log = F, main = paste("k=", k.vector[k]), sub = paste("Cophenetic coef.=", rho[k]), ylab = "samples", xlab ="samples")
}
y.range <- c(1 - 2*(1 - min(rho)), 1)
plot(k.vector, rho, main ="Cophenetic Coefficient", xlim=c(k.init, k.final), ylim=y.range, xlab = "k", ylab="Cophenetic correlation", type = "n")
lines(k.vector, rho, type = "l", col = "black")
points(k.vector, rho, pch=22, type = "p", cex = 1.25, bg = "black", col = "black")
dev.off()
I know this is a very old post and surely the OP has solved this. But I encountered this similar situation while working with plotly. Converting a ggplot output into a plotly output generated the similar error of not being able to open file 'Rplots.pdf'.
I solved it by simply including :
pdf(NULL)
I'm not sure of the reason for the error, have not been able to figure that out, but this small line helped removing the error and displaying my plots as I would expect in plotly and ggplot combinations.
I wonder if you have another command that opens a device before or after the code snippet you've given us. When you're all done run dev.cur() to see if there was a device left open. If not, it should return the null device.
Here are ways you can recreate getting a Rplots.pdf or a Rplot001.png; the layout and par commands open a device if one isn't open, and since no filename has been given, it uses the default filename.
options(device="pdf")
layout(1:4)
dev.off()
options(device="png")
par()
dev.off()
Maybe seeing that happen here will give you a clue as to what's happening with your code.
Here is the source code for CairoPNG:
function (filename = "Rplot%03d.png", width = 480, height = 480,
pointsize = 12, bg = "white", res = NA, ...)
{
Cairo(width, height, type = "png", file = filename, pointsize = pointsize,
bg = bg, ...)
}
This tells you that CairoPNG takes filename=... as a parameter, and passes this to Cairo as the file parameter.
I can see how this can lead to confusion, but the point is that your call to CairoPNG should be:
CairoPNG(filename="graphs.png")
See if that works...
I had a similar problem recently after upgrading to R-3.0.3 (yes we're a little behind!). It turns out that palette("default") opens a device now, though it didn't used to.

Resources