Unknown graphics device error in Rstudio - r

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="_")

Related

ggplot2: CairoSVG changes point size

I build scatterplots using ggplot2 in R. I then want to save them as svg files with Cairo::CairoSVG. It seems to work fine except for the point size, which is enlarged in the resulting .svg file.
Here comes some example code:
library (ggplot2)
my_plot <- ggplot(mpg, aes(cty, hwy)) +
geom_point(size = 0.5)
x11 (width = 6, height = 6)
my_plot
Cairo::CairoSVG (file = "my_path",
width = 6, height = 6)
print (my_plot)
dev.off()
And this is what I get: on the right hand, the plot printed in R and on the left side the saved .svg-file opened in Inkscape. It looks fine except for the point size, which is a pity. Are there any ideas on how to get the right point-size? I tried different point sizes and also shapes, with similarly unmatched results.
Note that I seek to stick with Cairo::CairoSVG, beacuse in the final plots I wish to use custom fonts which are printed nicely with Cairo::CairoSVG. Any help is appreciated.
EDIT: I am working on a Windows machine.
Preliminary remark: when you pass width = 6, height = 6 in the Cairo::CairoSVG() parameters, you provide potentially different parameters (resolution and display) from the ones used in the RStudio plot panel.
To get the exact same image than the one rendered in the panel as well as using Cairo, you can use this alternative (dev.size('px') returns the dimensions of the current plot panel):
library (ggplot2)
my_plot <- ggplot(mpg, aes(cty, hwy)) +
geom_point(size = 0.5)
my_plot
mirror <- recordPlot()
png(filename = "mypath",
width = dev.size('px')[1]/96,
height = dev.size('px')[2]/96,
res = 96, # base RStudio resolution
units = "in",
type = "cairo") # calls CairoSVG
replayPlot(mirror)
dev.off()
(Note : I prefer the use of png() rather than ggsave() because it will save the entire last plot. I have observed that ggsave() would save only the last facet of a grid, for example)

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.

Save ggplot object as image in the environment as object/value

I have a ggplot object. Let's call it plot. I would like to convert it to png format, but I don't want to save it to a file on my local drive. I'm trying to work with that png object but I want to keep everything in the environment. Everything I've found, including ggsave, appears to force one to save the image as a file on the local drive first. I know image files can be stored as values, but I can't seem to get over the "save as" image and "import" image steps.
Here's some code for repoducibility:
library(tidyverse)
df <- as.data.frame(Titanic)
gg <- ggplot(data = df, aes(x = Survived, y = Freq))
plot <- gg + geom_bar(stat = "identity")
Now, I'd like to convert plot to a png to png without having to save it to a file. Something like:
png <- save.png(plot)
Thanks for the help!
It looks like the goal here would be to convert plot (the ggplot object) directly to a Magick image that you can operate on with functions in the magick package. Something like this:
mplot = image_graph(width=400, height=500)
plot
dev.off()
image_graph opens a graphics device that produces a Magick image and assigns it to mplot so that you'll have the object available in your environment. Then, when you type mplot in the console, you'll see the following:
format width height colorspace matte filesize density
1 PNG 400 500 sRGB TRUE 0 +72x+72
However, when I try to display the mplot image (type mplot in the console), I see the following:
even though the original plot looks like this:
I'm not sure what's going wrong, but hopefully someone with greater familiarity with magick will drop by and provide a solution.
I was faced with a similar issue and followed #eipi12 approach of using magick. The code bellow should work:
library(ggplot2)
library(magrittr)
ggsave_to_variable <- function(p, width = 10, height = 10, dpi = 300){
pixel_width = (width * dpi) / 2.54
pixel_height = (height * dpi) / 2.54
img <- magick::image_graph(pixel_width, pixel_height, res = dpi)
on.exit(utils::capture.output({
grDevices::dev.off()}))
plot(p)
return(img)
}
p <- data.frame(x = 1:100, y = 1:100) %>%
ggplot(aes(x = x, y = y)) +
geom_line()
my_img <- ggsave_to_variable(p)
my_img %>%
magick::image_write("my_img.png")

Export R plot to multiple formats

Since it is possible to export R plots to PDF or PNG or SVG etc., is it also possible to export an R plot to multiple formats at once? E.g., export a plot to PDF and PNG and SVG without recalculating the plot?
Without using ggplot2 and other packages, here are two alternative solutions.
Create a function generating a plot with specified device and sapply it
# Create pseudo-data
x <- 1:10
y <- x + rnorm(10)
# Create the function plotting with specified device
plot_in_dev <- function(device) {
do.call(
device,
args = list(paste("plot", device, sep = ".")) # You may change your filename
)
plot(x, y) # Your plotting code here
dev.off()
}
wanted_devices <- c("png", "pdf", "svg")
sapply(wanted_devices, plot_in_dev)
Use the built-in function dev.copy
# With the same pseudo-data
# Plot on the screen first
plot(x, y)
# Loop over all devices and copy the plot there
for (device in wanted_devices) {
dev.copy(
eval(parse(text = device)),
paste("plot", device, sep = ".") # You may change your filename
)
dev.off()
}
The second method may be a little tricky because it requires non-standard evaluation. Yet it works as well. Both methods work on other plotting systems including ggplot2 simply by substituting the plot-generating codes for the plot(x, y) above - you probably need to print the ggplot object explicitly though.
Yes, absolutely! Here is the code:
library(ggplot2)
library(purrr)
data("cars")
p <- ggplot(cars, aes(speed, dist)) + geom_point()
prefix <- file.path(getwd(),'test.')
devices <- c('eps', 'ps', 'pdf', 'jpeg', 'tiff', 'png', 'bmp', 'svg', 'wmf')
walk(devices,
~ ggsave(filename = file.path(paste(prefix, .x)), device = .x))

error in rmarkdown when plotting

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.

Resources