How to save plots in code as they appear in the RStudio 'Plots' pane?

I often use the 'Plots' pane to work on plots and graphs before saving them to disk with png() or jpeg(). In larger scripts, it's often important to write to disk programmatically rather than clicking the 'Export' button from the IDE.

However, I find that my saved plots have different proportions, element placement, and axes than the plot that appears in the 'Plots' pane, even when saved with the exact same pixel dimensions. This can be a huge headache for more complicated plots with lots of elements or careful placement of labels.

To take a simple example:

png('rplot PNG.png', width=532, height=428)
title("Title", line = -2)

I can confirm in the IDE using 'inspect element' that my Plots pane is exactly 532x428 and produces this image. The same image appears using the 'Export' tool:
rplot IDE export

However, the code above outputs the following image:
rplot PNG

I can confirm on disk that both files are 532x428.

Does anyone know why this is? I have similar issues with ggplot2 but I figured using this base example might be best for now. I also tried evaluating different pointsize parameters for the png() method, with no luck.

> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.6.1 tools_3.6.1   

I was able to solve my ggplot use case by using with a width and height in the same units as ggsave:

width <- 6.5
height <- 4.2 = width, height = height, unit = "in", noRStudioGD =T)
ggsave("FIG0209.png", pt, width = width, height = height)
1 Like

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