My question is I want to integrate a d3.js visualization to my markdown rather than a link pointing to the visualization on external website. Is there a way to achieve that?
To accomplish adding nonlocal javascript such as d3.v3.min.js
to our Rmd, there are a couple ways to do it. If you are looking to include local copy of d3
, it is much easier.
This is my favorite way. If for some reason, you would like to see the others, I will be happy to show them. Note: I am still experimenting.
---
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>
then in the same directory as this .Rmd file, save this
<script src = "http://d3js.org/d3.v3.min.js"></script>
into a file I called header_include_d3.html
or whatever name you would like. If you change the name, just be sure to change the reference in the includes
in the yaml
of your Rmd.
As I said before, this is much easier if you have d3.js locally that you would like to use.
Also, <script src='...'></script>
inside the body will work if you are not particular about have your js in the header. In that case, just include it anywhere in the Rmd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With