Accepted answer

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"
    self_contained: false
    keep_md: true
      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'}

<script>"body").append("p").text("d3 made me")



// from
//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; })

//The SVG Container
var svgContainer ="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");


then in the same directory as this .Rmd file, save this

<script src = ""></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.


You have now the R2D3 package that allows that! Rmardown is one way of including D3 visualisation in R

Related Query