Plotly-在R中生成JSON,在html/javascript中保存和重用

use*_*239 7 javascript json r plotly

它有一个简单的示例,说明如何:

  1. 从 R 绘图中导出绘图 json 文件
  2. 保存此文件
  3. 使用plotly.js 库重用此文件在网页中生成绘图

我已经为绘图生成了 json 文件 (p1):

json<-plotly_json(p1,FALSE)
write(json,'test.json')
Run Code Online (Sandbox Code Playgroud)

但我无法在简单的 html/java 脚本测试中生成绘图。我已经能够在 html/javascipt 中生成绘图,而不是从 R 保存的 json 文件生成绘图。这看起来很简单,但我是 html 新手,显然缺少一些明显的东西。

img*_*atz 2

我想我终于得到了 OP 和我一直在寻找的东西。

下面的函数输出两个文件。

  1. Javascript 文件包含 Plotly 所需的所有内容
  2. 可选 HTML 文件,包含用于绘制绘图的适当代码。
rm(list = ls())


library(tidyverse)
library(stringi)
library(plotly)


plotly_to_js <- function(

  plotly.object
  , div.id = 'plot1'
  , output.html = FALSE
  , output.file = NULL
  , output.dir = NULL
  , output.url = NULL

){

  if(is.null(output.file)){
    output.file <- div.id %s+% '.js'
  }

  if(is.null(output.dir)){
    js.filename <- getwd() %s+% '/' %s+% output.file
  }else{
    js.filename <- output.dir %s+% '/' %s+% output.file
  }

  if(is.null(output.url)){
    output.url <- div.id %s+% '.html'
  }


  json <- plotly_json(plotly.object,FALSE)

  js.output <-
    "(function(){ \n
        window.PLOTLYENV={'BASE_URL': 'https://plotly.com'}; \n
        \n
        var gd = document.getElementById('%div.id%') \n
        var resizeDebounce = null; \n

        function resizePlot() { \n
          var bb = gd.getBoundingClientRect(); \n
          Plotly.relayout(gd, { \n
            width: bb.width, \n
              height: bb.height \n
            }); \n
          } \n

          Plotly.plot(gd,  \n
              %json%
           \n
                  ); \n
           }()); \n
  "

  js.output <- gsub('%div.id%', div.id, js.output)
  js.output <- gsub('%json%', json, js.output)

  fileConn<-file(js.filename)
    writeLines(js.output, fileConn)
  close(fileConn)

  if(output.html){

    output.html <-
      "<html> \n
        <head> \n
            <meta charset=\"utf-8\"/> \n
        </head> \n

        <body> \n
        \n
          <script src='https://cdn.plot.ly/plotly-latest.min.js'></script> \n
        \n
        <div id=\"%div.id%\" style=\"width: 100%; height: 100%;\" class=\"plotly-graph-div\"></div> \n
        <script type=\"text/javascript\" src=\"%js.filename%\"></script> \n

        </body>\n
        </html>\n"

    output.html <- gsub('%div.id%', div.id, output.html)
    output.html <- gsub('%js.filename%', js.filename, output.html)

    fileConn <- file(output.url)
      writeLines(output.html, fileConn)
    close(fileConn)

  }

}



x <- c(1:100)
random_y <- rnorm(100, mean = 0)
data <- data.frame(x, random_y)

fig <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines')

plotly_to_js (
  fig
  , output.html = TRUE
)

Run Code Online (Sandbox Code Playgroud)