如何在R Markdown中添加交互式可视化

15

我的问题是,我想将一个d3.js可视化图表集成到我的Markdown文档中,而不是提供一个指向外部网站的链接。有没有办法实现这一点?


2
你是在写什么样的可视化?是用ggvis还是d3自己编写的? - David Robinson
嗨@DavidRobinson,这是我自己编写的可视化。 - MYjx
@TylerRinker 我也在考虑使用 iframe,但是我该如何在 rmarkdown 中集成 iframe 呢? - MYjx
1
@MYjx:rmarkdown允许包含HTML。只需编写一些即可。 - David Robinson
我意识到这个问题比较模糊,所以现在正在努力提供一个真正的答案。 - timelyportfolio
显示剩余3条评论
2个回答

12
为了将非本地JavaScript,如d3.v3.min.js添加到我们的Rmd中,有几种方法可供选择。如果您想要包含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的includes中更改引用。

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

此外,如果您对将js放在头部不太关注,则<script src='...'></script>将在body内起作用。在这种情况下,只需在Rmd中的任何位置包含即可。


5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接