我的问题是我想将 d3.js 可视化集成到我的 Markdown 中,而不是指向外部网站上的可视化的链接。有没有办法实现这一目标?
最佳答案
完成添加非本地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
或任何你想要的名字。如果更改名称,请务必更改 includes
中的引用。在 yaml
你的 Rmd。正如我之前所说,如果您想在本地使用 d3.js,这会容易得多。
另外,
<script src='...'></script>
如果您不特别关注将 js 放在标题中,则 body 内部将起作用。在这种情况下,只需将它包含在 Rmd 的任何位置。
关于r - 如何将交互式可视化添加到 R markdown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25819539/