Skip to content

How to preview a plot using absolute size #1583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
toxintoxin opened this issue Jan 19, 2025 · 1 comment
Open

How to preview a plot using absolute size #1583

toxintoxin opened this issue Jan 19, 2025 · 1 comment

Comments

@toxintoxin
Copy link

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?

@ccsarapas
Copy link

ccsarapas commented Mar 25, 2025

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") { }.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants