要完成向我们的 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,则正文中的<script src='...'></script> 将起作用。在这种情况下,只需将它包含在 Rmd 中的任何位置。