0

I'd like to include a JSON tree in my rmarkdown result. Here's a reproducible example:

library(plotly)

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

plotly_json(p)

The object created by calling plotly_json(p) is "jsonedit" "htmlwidget".

While using this piece of code before knitting the result is presented in the Viewer. This is the way I want the result presented in html file.

However, having knitted the document to html I get the same result but in text form.

pogibas
  • 27,303
  • 19
  • 84
  • 117
balkon16
  • 1,338
  • 4
  • 20
  • 40

1 Answers1

2

From the source code of plotly_json, it seems that you need to manually set jsonedit to true, and have listviewer package installed.

The default for jsonedit is interactive():

Return TRUE when R is being used interactively and FALSE otherwise.

Which explains why the widget shows up when you execute the code directly, but not showing when you knit the rmd file.

try this:

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'

Created on 2018-07-19 by the reprex package (v0.2.0.9000).

TC Zhang
  • 2,757
  • 1
  • 13
  • 19