Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Last active April 30, 2017 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timelyportfolio/cbc31718ffdf39dd838a86cb94f70cc1 to your computer and use it in GitHub Desktop.
Save timelyportfolio/cbc31718ffdf39dd838a86cb94f70cc1 to your computer and use it in GitHub Desktop.
vue d3 treemap in Rmd

This is a R markdown version of the vue d3 treemap example. Rmd allows us to stay closer to our R context and also takes fuller advantage of the vueR package helpers. If we separated out the <template></template> and <script>...</script> piece into a JavaScript .js file, then the Rmd would be even cleaner and entirely R.

View the Rmd in raw to see everything.

```{r}
library(treemap)
library(vueR)
library(d3r)
library(htmltools)
rhd <- random.hierarchical.data()
rhd_json <- d3_nest(rhd, value_cols="x")
```
<template id="d3treemap">
<svg v-bind:style="styleObject">
<g>
<rect v-for="(node, index) in nodes" v-if="node.depth === 2" v-bind:x="node.x0" v-bind:width="node.x1 - node.x0" v-bind:y="node.y0" v-bind:height="node.y1 - node.y0" v-bind:style="{fill: color(node.parent.data.name)}"></rect>
</g>
</svg>
</template>
<script>
Vue.component('treemap-component', {
template: '#d3treemap',
props: {
tree: Object,
sizefield: {
type: String,
default: 'size'
},
treewidth: {
type: Number,
default: 400
},
treeheight: {
type: Number,
default: 400
},
tile: {
type: Function,
default: d3.treemapSquarify
},
color: {
type: Function,
default: d3.scaleOrdinal(d3.schemeCategory10)
}
},
computed: {
styleObject: function() {
return {width: this.treewidth, height: this.treeheight}
},
treemap: function() { return this.calculate_tree() },
nodes: function() {
var color = this.color;
var nodes = [];
this.treemap.each(function(d) {
nodes.push(d);
});
return nodes;
}
},
methods: {
calculate_tree: function() {
var sizefield = this.sizefield;
var d3t = d3.hierarchy(this.tree)
.sum(function(d) {
return d[sizefield]
});
return d3.treemap()
.size([this.treewidth, this.treeheight])
.tile(this.tile)
.round(true)
.padding(1)(d3t)
}
}
});
</script>
```{r}
tagList(
tags$div(
id="app",
tag(
"treemap-component",
list(":tree" = "tree",":sizefield"="'x'") #use defaults
)
),
vue(
list(
el = "#app",
data = list(
tree = rhd_json,
size = 'x',
width = 800,
height = 600,
tile = htmlwidgets::JS("d3.treemapSliceDice")
)
)
),
d3_dep_v4()
)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment