【问题标题】:Error: "HTML widgets cannot be represented in plain text"错误:“HTML 小部件不能以纯文本表示”
【发布时间】:2017-10-16 12:26:37
【问题描述】:

当我尝试通过 Jupyter 运行它时:

library(leaflet)

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
m  # Print the map

我收到此错误:

HTML widgets cannot be represented in plain text (need html).

按照here的建议,我试过了:

library(plotly)
embed_notebook(m)

但我明白了:

Error in UseMethod("embed_notebook"): no applicable method for 'embed_notebook' applied to an object of class "c('leaflet', 'htmlwidget')

我怎样才能画出这种图?

【问题讨论】:

    标签: r jupyter


    【解决方案1】:

    embed_notebook 是专门为 plotly 对象定义的。我会查看文档,看看传单是否有自己的等效功能。

    或者,由于它是一个 html 小部件,您可以将其保存为 html 文件,然后将该文件嵌入到笔记本的 iframe 中。这可以通过类似的方式来完成

    library(IRdisplay)
    htmlwidgets::saveWidget(m, "m.html")
    display_html('<iframe src="m.html" width=100% height=450></iframe>')
    

    如果您不想在文件夹中保留一堆 html 文件,您也可以将小部件的原始 html 输入到 iframe 中,然后使用删除它

    rawHTML = base64enc::dataURI(mime = "text/html;charset=utf-8", file = "m.html")
    display_html(paste("<iframe src=", rawHTML, "width=100% height=450></iframe>", sep = "\""))
    unlink("m.html")
    

    但我发现这会在最新版本的 Chrome 中产生错误。

    如果有帮助,我从 embed_notebook 的源代码中拼凑出以下函数

    embed = function(x, height) {
        library(IRdisplay)
        tmp = tempfile(fileext = ".html")
        htmlwidgets::saveWidget(x, tmp)
        rawHTML = base64enc::dataURI(mime = "text/html;charset=utf-8", file = tmp)
        display_html(paste("<iframe src=", rawHTML, "width=100% height=", height, "id=","igraph", "scrolling=","no","seamless=","seamless", "frameBorder=","0","></iframe>", sep = "\""))
        unlink(tmp)
    }
    

    但同样,这可能不适用于 Chrome。

    【讨论】:

    • #cromulent 问题是 htmlwidgets::saveWidget(m, "m.html") 没有创建 html 文件。
    • @Simone 如果这是侮辱,我深表歉意,但是您是否在您的 R 版本中安装了 htmlwidgets 包?如果你这样做了,我没有足够的经验知道是什么导致了你的问题。
    • 是的,我已经安装了htmlwidgets
    • @cromulent 当我在 Jupyter 的 R 内核上运行时,它也不会为我创建 html 文件。在 RStudio 中运行良好。我在 JupyterHub 上没有 pandoc,所以设置了 selfcontained = FALSE,但是还有什么可以阻止它在 Jupyter 中运行的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    相关资源
    最近更新 更多