Unable to save plots in R using jpeg() or png()
1
0
Entering edit mode
14 months ago
manaswwm ▴ 550

Hello all,

I have recently come across a peculiar error in R and I wanted to know if anyone here has any idea on how can it be solved. Here is some background- I am currently writing a pipeline which has multiple functions that are all "called" from a single central script. One of these functions involves generating multiple plots and saving them in a specified folder. I am using jpeg() function in R for making these plots, here is an example:

    #opening the barplot save code
    jpeg(paste(backup_file, "plot.jpg", sep = ""), width = 12, height = 10, units = "in", res = 300)

    #making enrichment plot
    barplot(x)

    #closing the connection
    dev.off()

Here is the problem - when I "call" this function from the central script, it does not generate any plots (also does not give any errors). However, when I go to this function and run the code line-by-line, then the script does indeed generate the required plots.

Anyone know why this might be happening? Why a "call" to the function does not generate plot but running the code line-by-line does generate plot? I am using R version - 4.3.1 (2023-06-16) and Rstudio 2023.03.0+386 Cherry Blossom (server)

Thanks in advance for any help!

R visualization • 2.7k views
ADD COMMENT
0
Entering edit mode

Does it work if you add a dev.off() before calling jpeg?

ADD REPLY
0
Entering edit mode

I tried doing that but it gives this error now - Error in dev.off() : cannot shut down device 1 (the null device). Probably understandable because there is no open connection?

ADD REPLY
3
Entering edit mode
14 months ago
Barry Digby ★ 1.3k

Try printing the plot

bp = barplot(x)
jpeg(paste(backup_file, "plot.jpg", sep = ""), width = 12, height = 10, units = "in", res = 300)
print(bp) # or just bp
dev.off()
ADD COMMENT
2
Entering edit mode

Thanks! The trick of printing the plot does work. However, I also figured out that I can just use the ggsave function from ggplot instead, that way I do not have to do dev.off() everytime. I was under the impression that ggsave only works for plots made with ggplot but apparently that does not seem to be the case. For anyone interested, in addition to printing the plot, this is also one other way of doing it:

#making enrichment plot
barplot = barplot(x)

#saving with ggsave
ggsave(filename = paste(backup_file, "barplot.jpg", sep = ""), plot = barplot,
       dpi = 300, height = 10, width = 12, device = "jpeg")
ADD REPLY

Login before adding your answer.

Traffic: 1927 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6