How to preview a plot using absolute size
As a researcher, the main purpose of plotting is to put it in my article, I usually specify the base_size as 7 in the ggplot2's theme() to meet the journal's requirements, and then save it as svg with ggsave(), specifying, for example, the width as 40mm and the height as 32mm.
But in order to confirm the effect, I need to keep switching between vscode and edge. Is there any way to preview it directly in httpgd?
I don't think this is supported (either by the VSCode R extension or in RStudio). However, I had the same need so knocked together a pair of functions to display a plot at a specified size in VSCode.
vsview <- function(plot = ggplot2::last_plot(),
width = 6.5,
height = 4,
panel = 1, # can init multiple panels, then send different plots to different panels
units = c("in", "cm", "mm", "px"),
dpi = 300,
scale = 1,
limitsize = TRUE,
bg = "white",
device = NULL,
mustWork = NA,
...) {
filename <- normalizePath(
file.path(tempdir(), paste0("preview", panel, ".png")),
winslash = "/", mustWork = mustWork
)
ggplot2::ggsave(
filename, plot,
device = device, scale = scale, width = width,
height = height, units = units, dpi = dpi, limitsize = limitsize, bg = bg,
...
)
invisible(filename)
}
vsview_init <- function(panel = 1, vscode_path = getOption("editor")) {
plot <- ggplot2::ggplot()
bg <- "gray35"
filename <- vsview(plot = plot, panel = panel, bg = bg, mustWork = FALSE)
system2(vscode_path, shQuote(filename))
}
Use like:
library(ggplot2)
vsview_init() # open a "viewer pane" in VSCode
p <- ggplot(mpg, aes(cty, hwy)) +
geom_point()
vsview(p, w = 7, h = 4)
I put this in my user .Rprofile inside if (Sys.getenv("TERM_PROGRAM") == "vscode") { }.