API 具有 R 管道工和 Plotly 异常错误的端点

API Endpoints with R Plumber and Plotly Exception Error

假设我的plumber.r文件的内容如下。我可以通过使用 chrome 访问路径并查看除 \plotly 端点之外的预期输出来成功测试每个端点。

在我的浏览器(即 http://localhost:8000/plotly)中访问它时,我得到“发生异常错误”。我没有使用 R Studio,我使用

从 RGui 会话启动它
pr("plumber.R") %>%  pr_run(port=8000)

关于我的错误在哪里有什么建议吗?

###plumber.R

library(plotly)
#* Plot a histogram
#* @serializer png
#* @get /plot
function() {
  rand <- rnorm(100)
  hist(rand)
}

#* Return the sum of two numbers
#* @param a The first number to add
#* @param b The second number to add
#* @get /sum
function(a, b) {
  as.numeric(a) + as.numeric(b)
}

#* Echo back the input
#* @get /dat
function() {
  data.frame(id = c(1,2,3,4), v2 = c(5,6,7,8))
}

#* @apiTitle HTML widgets API#* @apiTitle HTML widgets API
#* Return interactive plot using plotly
#* @serializer htmlwidget
#* @get /plotly
function() {
    fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
    fig
}

正在编辑以展示如何使用 Pandoc 解决此问题

我使用的是 Vanilla RGui 4.1.3 而不是 RStudio IDE。所以,我手动安装了 Pandoc 2.17.1.1。按照下面@jpiversen 的建议,我做了以下事情。

我先手动setwd()到本地安装Pandoc的位置。我需要这个,因为 htmlwidgets:::find_pandoc() 没有路径参数,它会扫描目录。设置工作目录后,然后运行

htmlwidgets:::find_pandoc()
htmlwidgets:::.pandoc$version
htmlwidgets:::.pandoc$dir

这解决了问题,我现在可以查看绘图端点。

根据评论更新

错误信息:

<simpleError in htmlwidgets::saveWidget(val, tmpfile, selfcontained = TRUE, ...): Saving a widget with selfcontained = TRUE requires pandoc. For details see: github.com/rstudio/rmarkdown/blob/master/PANDOC.md>

似乎对应于函数 plumber::serializer_htmlwidget() 调用 htmlwidget::saveWidget().

htmlwidget::saveWidget() 的源代码中,我们可以看到确切的错误消息是由 !pandoc_available() 触发的。

htmlwidget::pandoc_available()rmarkdown::pandoc_available() 不同,不知何故它找不到你的 pandoc。尝试 运行宁:

htmlwidgets:::find_pandoc()
htmlwidgets:::.pandoc$version
htmlwidgets:::.pandoc$dir

原回答

这似乎 运行 没问题 - 可能只是您在 Swagger 中看不到它。

如果你 运行 这来自 swagger,你会得到情节所需的 HTML-code:

但是如果您改为在浏览器中转到 http://127.0.0.1:8000/plotly,您应该会看到 plotly 小部件:

Sorry about the small image size.