3.4 Plot Viewer

VS Code has a built-in plot viewer that looks like this: ↩︎

What I don’t like about the built-in plot viewer

  • Weird aspect ratio and zoom, labels look very small
  • auto-resize is bad

httpgd: A graphics device for R that is accessible via HTTP and WebSockets. A clear distinction from the built-in VS Code plot panel is that there is a url as tab name on the top of the browser viewer. httpgd was created to make it easier to embed live R graphics in integrated development environments and other applications. httpgd is required by the interactive plot viewer of the R extension for VS Code.

A preview of httpgd plot viewer in VS Code:

Benefits of httpgd plot viewer:

  • Auto-resizing is good

  • Interactive

  • History plots, save as svg/png, delete, clear

    svg images are convenient for html reports. Best display quality as it is a vector file that allows for rescale without loss of quality or becoming pixelated.

Useful resources:


Setup httpgd in VS Code

  1. Install httpgd package in R

    install.packages("httpgd")
  2. Enable r.plot.useHttpgd in VS Code settings.

    {
      "r.plot.useHttpgd": true
    }
    • r.plot.useHttpgd: use the httpgd-based plot viewer instead of the base VSCode-R plot viewer

    This will allow you to view plots in a separate window or in the browser, which is useful for interactive visualizations.


3.4.1 Quick Start with httpgd

> library(httpgd)
# Start the httpgd graphics device
> hgd()
httpgd server running at:
  http://127.0.0.1:49724/live?token=QTikqshP

# Open the plot viewer in your browser
> hgd_browse()

# Create a figure
> x = seq(0, 3 * pi, by = 0.1)
> plot(x, sin(x), type = "l")

Q: Plot viewer is missing or you accidentally closed it.
A: Run hgd_browse() to re-open the browser viewer.

If you don’t have any httpgd client open, say you had run hgd_close(), then first run hgd() in R and an url will be shown in the R console. Then run hgd_browse() to open the url in the internal browser viewer. Alternatively, use the command palette to run “R Plot: Open httpgd Url”. It will let you enter the url address, fill it in and hit Enter to open the plot viewer. You can also copy and paste the url in an external browser.

When you call hgd() and hgd_browse(), it will start the httpgd web server and open the plot viewer in a new tab. You will see the url, e.g., http://127.0.0.1.<port>/live?token=... in the address bar of the viewer.


Issue: When you plot a new figure, it will show both in the VS Code plot panel and the browser viewer. It’s like one device with two clients: the VS Code plot panel and the browser viewer. The browser viewer is more interactive and has better display quality, so I prefer to use the browser viewer.

Fix: Open a plot directly in my httpgd browser without opening it inside VS Code plot panel. Add the following to your .Rprofile:

# Source - https://stackoverflow.com/a/75183587
# Posted by MarBlo

if (interactive() && Sys.getenv("RSTUDIO") == "") {
  source(file.path(Sys.getenv(
    if (.Platform$OS.type == "windows") "USERPROFILE" else "HOME"
  ), ".vscode-R", "init.R"))
  if ("httpgd" %in% .packages(all.available = TRUE)) {
    options(vsc.plot = FALSE, vsc.use_httpgd = FALSE)
    options(device = function(...) {
      httpgd::hgd(silent = TRUE)
      .vsc.browser(httpgd::hgd_url(history = FALSE), viewer = TRUE)
    })
  }
}

viewer = TRUE to open the plot viewer in a new internal WebView tab in VS Code. Set viewer = FALSE will open the plot viewer in an external browser.


Commonly used functions in httpgd: ↩︎

  • hgd() Initialize device and start server.

  • hgd_browse() Open the plot viewer in your browser, can be internal or external.

    hgd_browse() is equivalent to running “R Plot: Open Httpgd Url” in the command palette.

    > hgd()
    httpgd server running at:
      http://127.0.0.1:58118/live?token=Ka9j9ziG
    
    > hgd_browse()
    Browsing http://127.0.0.1:58118/live?token=Ka9j9ziG

    When you call hgd_browse(), it will open the graphic device in a new tab in your default web browser. You wil see the path to the viewer in the R console.

    You may copy and paste the url to your external browser.

    There is an url in the tab header indicating it is a web browser.

    Click to open the viewer in an external browser.

    Click in the tool bar to refresh the viewer.

    When you hover over the image, a menu bar will show up. You can choose to download, copy, clear all plots, etc.

    # Stop the browser server with:
    dev.off(which = dev.cur())
    
    # If you have multiple devices open, close all devices with:
    graphics.off()
  • hgd_close() will close the httpgd device.

    Equivalent to dev.off().

    Note that this will NOT close the viewer window automatically for you. You can close the viewer manually by clicking the “x” button on the top right corner of the viewer window.

    By the next time you call plot, you will see all historical plots are gone.

    Closing the plot viewer window does not clear the plots, nor clearing the plots closes the plot viewer window.

    If you don’t call hgd_close(), but click the “x” button on the top right corner of the viewer window, the viewer will be closed but all historical plots are still there. You can call plot again to see the previous plots.

    Otherwise, if you click the “x” button directly, the viewer will be closed, but all historical plots are still there. You can call plot again to see the previous plots.

  • hgd_url() will return the url of the viewer.

    If you accidentally close the viewer, you can call hgd_url() to get the url and open it again. You can also copy and paste the url to your external browser.


Keyboard shortcut in the WebView

  • ←/→/↑/↓: navigate through the plot history

    Use ←/→ to navigate to the last/next plot. ✅

    ↑/↓ is strange as ↑ goes to next while ↓ goes to last… ❌

  • +/-: zoom in/out

  • 0: reset zoom

  • s/p: save the current plot as SVG/PNG

    Not recommended to save as PNG as the resolution is low.

    Use ggsave("plot.png", dpi = 300) instead to save high-resolution plots.


3.4.2 Configuration

Nice settings to make the plot viewer run more smoothly: make httpgd the default plot viewer in VS Code and open the viewer in a new tab beside the editor.

Add to .Rprofile

if (interactive() && Sys.getenv("TERM_PROGRAM") == "vscode") {
  if ("httpgd" %in% .packages(all.available = TRUE)) {
    options(vsc.plot = FALSE)
    options(device = function(...) {
      httpgd::hgd(silent = TRUE)
      .vsc.browser(httpgd::hgd_url(), viewer = "Beside")
    })
  }
}

It disables the original simple plot watcher provided by vscode-R session watcher (which replays user graphics into a png file) and use httpgd as the graphics device and opens a new WebView tab in VSCode to show the graphics.


Useful shortcuts for the plot viewer: Open current httpgd window if closed (ctrl + opt + p).

{
  "key": "ctrl+alt+p",
  "command": "r.runCommand",
  "when": "editorTextFocus && editorLangId == 'r'",
  "args": ".vsc.browser(httpgd::hgd_url(), viewer = \"Beside\")"
}

Universal graphics device (unigd) is a package that provides a set of functions to manage the plot viewer, such as:

  • unigd::ugd_clear() Clear all pages in the plot viewer.

    Same effects as hgd_close().

  • unigd::ugd_remove(page = 2) Remove the second page.