【问题标题】:How to add an interactive visualization to R markdown如何将交互式可视化添加到 R markdown
【发布时间】:2014-09-13 03:28:47
【问题描述】:

我的问题是我想将 d3.js 可视化集成到我的降价中,而不是指向外部网站上的可视化的链接。有没有办法做到这一点?

【问题讨论】:

  • 什么样的可视化? ggvis 还是 d3 你自己写的?
  • iframe 怎么样?
  • 嗨@DavidRobinson 这是我自己写的可视化
  • @TylerRinker 我也在考虑 iframe 但我如何将 iframe 集成到 rmarkdown 中?
  • @MYjx:rmarkdown 允许包含 HTML。随便写一点。

标签: r d3.js r-markdown


【解决方案1】:

要完成向我们的 Rmd 添加非本地 javascript(例如 d3.v3.min.js),有几种方法可以做到这一点。如果您希望包含 d3 的本地副本,那就容易多了。

这是我最喜欢的方式。如果出于某种原因,你想看看其他人,我很乐意展示给他们看。 注意:我仍在试验中。

---
title: "rmarkdown example with external js"
output:
  html_document:
    self_contained: false
    keep_md: true
    includes:
      in_header: "header_include_d3.html"
---

Let's create a very basic d3 graph using data from R.  since the graph is d3, we will need the d3.js file for the graph to render.

```{r results='asis'}

cat('
<script>
  d3.select("body").append("p").text("d3 made me")
</script>
')

```

<script>

// from https://www.dashingd3js.com/svg-paths-and-d3js
//The data for our line
 var lineData = [ { "x": 1,   "y": 5},  { "x": 20,  "y": 20},
                  { "x": 40,  "y": 10}, { "x": 60,  "y": 40},
                  { "x": 80,  "y": 5},  { "x": 100, "y": 60}];

 //This is the accessor function we talked about above
 var lineFunction = d3.svg.line()
                          .x(function(d) { return d.x; })
                          .y(function(d) { return d.y; })
                         .interpolate("linear");

//The SVG Container
var svgContainer = d3.select("body").append("svg")
                                    .attr("width", 200)
                                    .attr("height", 200);

//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
                            .attr("d", lineFunction(lineData))
                            .attr("stroke", "blue")
                            .attr("stroke-width", 2)
                            .attr("fill", "none");

</script>

然后在与这个.Rmd文件相同的目录下,保存这个

<script src = "http://d3js.org/d3.v3.min.js"></script>

放入我称为header_include_d3.html 或您想要的任何名称的文件中。如果您更改名称,请务必在您的 Rmd 的 yaml 中更改 includes 中的引用。

正如我之前所说,如果您在本地拥有想要使用的 d3.js,这会容易得多。

此外,如果您不特别想在标题中包含您的 js,则正文中的&lt;script src='...'&gt;&lt;/script&gt; 将起作用。在这种情况下,只需将它包含在 Rmd 中的任何位置。

【讨论】:

    【解决方案2】:

    您现在有了R2D3 包,它允许这样做! Rmardown 是在 R 中包含 D3 可视化的一种方式 https://rstudio.github.io/r2d3/articles/publishing.html#r-markdown

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多