原因未知。

1. 首次尝试 failed

现在可以逐行执行了,但是要在新开的浏览器查看图片:

# J3 server: CentOS 7.9
# 客户端是win10,使用 vscode ssh remote 连接到server

# install.packages("httpgd")
library(httpgd)
# library(httpgd, lib.loc = "/datapool/wangjl/R/x86_64-pc-linux-gnu-library/4.3.3") #if on J1
hgd()
httpgd::hgd_url() # 把输出的 url 复制到浏览器,查看接下来的绘图
# 同样打开设置面板,搜索 r.plot.usehttpgd,勾选 开启即可。

x = seq(0, 3 * pi, by = 0.1)
plot(x, sin(x), type = "l")
  • 支持拖拽改变长宽
  • 浏览器快捷键:d 删除当前图片,箭头键切换图片

(2)httpgd 提供了 hgd() 和 hgd_browse() 两个核心函数,你可以在出错时直接重新启动 [可能会异常退出R session]

library(httpgd)
# 检查服务器是否还活着

hgd()  # 重新启动
hgd_browse()  # 重新在浏览器中打开(VSCode 扩展也会自动检测)

可以绘图了

2.能work的好方法

## 打开图片:
library(httpgd) #载入包
# ‌检查设备‌
dev.list() #NULL 表示没打开过。有 unigd 表示已经打开过。

# (1)first open
hgd_close() #先关闭,再打开新的 初始化
# hgd() # 格式类似: http://127.0.0.1:38472/live?token=vf9Dwvka
hgd(port = 38888)  # 第一次初始化,可以指定端口

# (2)then reuse:
hgd_details() # 1)construct URL by hand
# 2)then goto vscode PORTS panel, click the "Preview in Editor"
# 3)paste the URL to the location region, click enter.

(2)包装成函数

library(httpgd)
start_hgd <- function(port=-1) {
  # 检查当前设备列表
  dev_list <- dev.list()
  #if (!is.null(dev_list) && any(grepl("httpgd", names(dev_list)))) {
  if (!is.null(dev_list) && any(grepl("unigd", names(dev_list)))) {
    message("httpgd 设备已存在,无需重新启动。")
  } else {
    # 仅在不存在时启动初始化语句
    if(port!=-1){ hgd(port = port); }
    else { hgd(); }
  }
  w=hgd_details()
  msg=sprintf("Go ports panel, click View in editor, and paste this url:\n\thttp://%s:%s/live?token=%s\nstatus: %s\n",
    w$host, w$port, w$token, w$status)
  cat(msg)
}

# 然后每次画图前调用:
start_hgd(38888)
plot(1:10)

Ref

  • https://github.com/REditorSupport/vscode-R/wiki/Plot-viewer
  • https://forum.posit.co/t/opening-httpgd-plot-in-external-window-through-vscode-workbench-proxy-server/188572
  • https://github.com/REditorSupport/vscode-R/wiki/R-Session-watcher

更多推荐