block by timelyportfolio 34296462d01cc80915d1f01431723763

sankeytree 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.

library(d3r)
library(dplyr)
library(htmltools)
library(treemap)
#devtools::install_github("https://github.com/Displayr/rhtmlSankeyTree")
library(sankeytreeR)

titan_tree <- as.data.frame(Titanic) %>%
  select(-Age) %>%
  group_by(Class, Sex, Survived) %>%
  summarise(Freq = sum(Freq)) %>%
  treemap(index=c("Class", "Sex", "Survived"), vSize="Freq") %>%
  {.$tm} %>%
  rename(size = vSize) %>%
  mutate(color = mapply(
    function(Sex,Survived,color) {
      if(is.na(Sex)){ return("gray") }
      print(c(Sex,Survived,color))
      if(Sex=="Male" && is.na(Survived)){ return("cadetblue")}
      if(Sex=="Female" && is.na(Survived)){ return("pink")}
      if(!is.na(Survived)&&Survived=="No") {return("red")}
      if(!is.na(Survived)&&Survived=="Yes") {return("green")}
    },
    Sex,
    Survived,
    color,
    SIMPLIFY = FALSE
  )) %>%
  select(1:4, color) %>%
  d3_nest(value_cols=c("size","color"), root="Titanic", json=FALSE) %>%
  mutate(size = sum(Titanic), color="#F0F") %>%
  d3_json(strip=TRUE)

sankeytree(titan_tree, maxLabelLength=15, treeColors=FALSE)