[英]How to add an interactive visualization to R markdown
我的問題是我想將d3.js可視化集成到我的markdown而不是指向外部網站上的可視化的鏈接。 有沒有辦法實現這一目標?
為了實現增加非本地的JavaScript如d3.v3.min.js
我們RMD,有幾種方法可以做到這一點。 如果您希望包含d3
本地副本, 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中的任何位置即可。
你現在有R2D3包允許這樣做! Rmardown是在R中包含D3可視化的一種方式https://rstudio.github.io/r2d3/articles/publishing.html#r-markdown
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.