block by timelyportfolio c7ae4661d58b78b50fe662dd02d32b7d

d3.tree() on Titanic

Full Screen

This example courtesy of Displayr who have generously offered to sponsor a series of independently authored posts about interactive visualization with R and JavaScript. Thank you so much Displayr for this opportunity.


Code in R

Below is the R source code for creating this visualization. You might notice that much of this is actually JavaScript. To see the JavaScript, please inspect index.html.

library(d3r)
library(dplyr)
library(htmltools)
titan_nest <- as.data.frame(Titanic) %>%
  select(-Age) %>%
  group_by(Class, Sex, Survived) %>%
  summarise(Freq = sum(Freq)) %>%
  d3_nest(value_cols="Freq", root="Titanic")

browsable(
  tagList(
    d3_dep_v4(offline=FALSE),
    tag("svg", list(id="tree", height=600, width=800)),
    tags$script(HTML(
sprintf("
  var titanic = %s;
  var tree = d3.tree()
    .size([400, 750])(d3.hierarchy(titanic));

  var tree_g = d3.select('#tree')
    .append('g')
    .attr('transform', 'translate(20,20)');

  var nodes = tree_g.selectAll('.node')
    .data(tree.descendants())

  nodes = nodes.merge(
    nodes
      .enter()
      .append('g')
      .classed('node', true)
  )

  var color = d3.scaleOrdinal(d3.schemeCategory10);
  nodes
    .attr('transform', function(d) {
      return 'translate(' + d.y + ',' + d.x + ')';
    });

  nodes
    .append('rect')
    .attr('height', 10)
    .attr('width', 5)
    .attr('y', -5)
    .style('fill', function(d) {
      return color(d.data.name);
    })

  nodes
    .append('text')
    .text(function(d){
      return d.data.name
    })
    .attr('dy', function(d) {
      if(d.height===0) {return 5}
      return -5
    })
    .attr('dx', function(d) {
      if(d.height===0) {return 5}
      return -2
    })
    .attr('text-anchor', 'beginning')
    .style('font-size', '10px')
    .style('fill', function(d) {
      return color(d.data.name);
    })

  var links = tree_g.selectAll('.link')
    .data(tree.links());

  links = links.merge(
    links.enter()
      .append('path')
      .classed('link', true)
  )

  links
    .attr(
      'd',
      d3.linkHorizontal()
        .x(function(d) { return d.y; })
        .y(function(d) { return d.x; })
    )
    .style('fill', 'none')
    .style('stroke', function(d) {
      return color(d.target.data.name);
    })
",
titan_nest
)
    ))
  )
)

index.html