Home > Software design >  How do I conveniently resize a ggplot2 plot on R VSC?
How do I conveniently resize a ggplot2 plot on R VSC?

Time:01-23

I'm in the process of learning R (I'm still a newcomer on SO as well). Being very used to using Visual Studio Code, I decided to choose that over RStudio or RStudio Cloud.

One of the best parts of RStudio was that plots automatically resized/reshaped themselves if we resized the right pane. Moreover, in the tutorials I watched, plots involving map data automatically rendered in the correct aspect ratio (as seen on physical maps).

I replicated the code to make my own plot of the world map. Unfortunately it rendered as a square shape, and resizing the right pane does not affect its shape:

enter image description here

Am I missing any commonly used VSC extensions which can make plots resizeable like in RStudio? (I've installed only the most downloaded extension for R, by Yuki Ueda)

If not, can I modify my code to specify the exact dimensions I need the plot to have?

Thanks in advance!

CodePudding user response:

You can specify the dimensions when you save the file. I usually use (approximately) the golden ratio:

ggsave("./earth.png", width = 16, height = 10)

The ggsave function reference explains how you can change units - options are c("in", "cm", "mm", "px").

CodePudding user response:

You can add robust plot viewing options for R in VSCode by installing the httpgd package and then amending your JSON settings.

First, install httpgd via the R console:

install.packages("httpgd")

Then, open your JSON settings in VSCode by opening the Command Palette (either via Ctrl Shift P or via View > Command Palette) and then searching for "Preferences: Open Settings (JSON)", where you'll insert the following:

"r.plot.useHttpgd": true

You can add a comma after 'true' if needed (i.e. if there are other lines below that in your JSON settings).

Following that, restart VSCode and launch the R terminal inside it, and plot something using either ggplot2 or base R graphics:

plot(mtcars$mgp, mtcars$wt)

A plot viewer should then pop up in VSCode. You can either manually resize the window there, zoom in or out, or, my preference (particularly if I'm cycling through a series of already-plotted graphs), open it in an external browser where it'll automatically adjust to however you resize the window. After that, you can save or copy the image as needed.

  •  Tags:  
  • Related