Skip to content

How to preview a plot using absolute size #1583

Description

@toxin98

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?

Activity

  1. ccsarapas commented on Mar 25, 2025

    @ccsarapas

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

  2. ThomasSoeiro commented on Sep 22, 2026

    @ThomasSoeiro
    Collaborator

    @grantmcdermott perhaps it can either be closed as not planed or added it to a milestone?

  3. locked and limited conversation to collaborators on Sep 22, 2026
  4. converted this issue into a discussion #1748 on Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions