首页 > 解决方案 > rmarkdown 中的 JSON 树

问题描述

我想在我的 rmarkdown 结果中包含一个 JSON 树。这是一个可重现的示例:

library(plotly)

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
   geom_point() + geom_smooth()

plotly_json(p)

调用创建的对象plotly_json(p)"jsonedit" "htmlwidget".

在编织之前使用这段代码时,结果会显示在Viewer中。这是我希望结果呈现在 html 文件中的方式。

但是,将文档编织为 html 后,我得到了相同的结果,但采用的是文本形式

标签: rjsonggplot2plotlyhtmlwidgets

解决方案


从 plotly_json 的源代码看来,您似乎需要手动设置jsonedit为 true,并安装listviewer包。

jsonedit 的默认值是 interactive():

当 R 被交互使用时返回 TRUE,否则返回 FALSE。

这就解释了为什么当你直接执行代码时显示小部件,但在你编织 rmd 文件时没有显示。

尝试这个:

library(plotly)
#> Loading required package: ggplot2
#> 
#> Attaching package: 'plotly'
#> The following object is masked from 'package:ggplot2':
#> 
#>     last_plot
#> The following object is masked from 'package:stats':
#> 
#>     filter
#> The following object is masked from 'package:graphics':
#> 
#>     layout
# install required listviewer pkg if necessary
#install.packages("listviewer")

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
   geom_point() + geom_smooth()

# use jsonedit from listviewer pkg
plotly_json(p, jsonedit = TRUE)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

reprex 包(v0.2.0.9000)于 2018 年 7 月 19 日创建。


推荐阅读