cannot export plots to pdf (file corrupted, dev off gives "RStudioGD@")

I am trying to print plots to pdf but first received some warning that device 1 cannot be turned off, now I receive only "RStudioGD2". What am I missing here?

the code is:

o <- function(x){ 
  qqnorm(x)
  qqline(x)}

qqploty <- (lapply(mtcars, o))

pdf("qqploty.pdf")
qqploty
dev.off()

Hello,

This issue with regular R plots is that they are immediately written to the output and cannot be stored in a variable like that. Use the recordPlot to save the current plot output to a variable, then you can save it.

o <- function(x){ 
  qqnorm(x)
  qqline(x)}

lapply(mtcars, o)
qqploty <- recordPlot()

pdf("qqploty.pdf")
qqploty
dev.off()

Your function looks a bit weird to me, but that's probably because this is a reprex, not the actual code. You can also consider using ggplot as this is more versatile and powerful than basic plot and you have more control over assigning variables, updating and plotting them.

Hope this helps,
PJ

1 Like

Hello, thanks for responding.

I tried the code you wrote and indeed, it makes a pdf but with only the last one plot...

You say there is no way to store standard plots in a variable here? Would it be possible with a ggplot ?

( I found e.g. this:

library(tidyverse)

oo <- function(x) {
  ggplot() + geom_qq(aes(sample = x)) + geom_qq_line()
}

ploty <- lapply(mtcars,oo)

pdf("sploty.pdf")
ploty
dev.off()

which seems to work alright, except +geom_qq_line() does not show the line)

PS. why the function is weird?
I tried to write it inline in lapply, it worked with a semicolon and looked less

Hi,

Here is the ggplot version

library(ggplot2)

oo <- function(x) {
  ggplot(data.frame(x = x)) + 
    geom_qq(aes(sample = x)) + 
    geom_qq_line(aes(sample = x))
}

ploty <- lapply(mtcars,oo)

pdf("test.pdf")
ploty
dev.off()

In ggplot, you need to provide a data frame in the first function and in subsequent functions call any column of it within aes(). Since what your function takes in is a vector, you first need to put it in a data frame then call it again.

I don't know what your goal is, but know that there are other ways of showing multiple plots using gridarrange, though this shows all plots as subplots of a big one.

PJ

Hello,
thanks for the code and the explanation.
The purpose here is only to eyeball plots for normality and keep it stored.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.