在rmarkdown中的JSON树

问题描述 投票:0回答:1

我想在我的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我得到了相同的结果,但在text form

r json ggplot2 plotly htmlwidgets
1个回答
2
投票

从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 package创建于2018-07-19(v0.2.0.9000)。

© www.soinside.com 2019 - 2024. All rights reserved.