Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Created December 8, 2016 15:33
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/49e92cc830e794d44018b0239612a466 to your computer and use it in GitHub Desktop.
Save timelyportfolio/49e92cc830e794d44018b0239612a466 to your computer and use it in GitHub Desktop.
hierarchy styling in formattable

Prompted by a tweet, I set out to write an example of illustrating hierarchy with the R package formattable. I used treemap to make some fake hierarchical data. Much of this code is cleaning the treemap data and can most likely be ignored.

library(treemap)
library(pipeR)
library(dplyr)
library(htmltools)

# make some fake data with treemap
tm <- random.hierarchical.data() %>>%
  treemap(
    index=c("index1","index2","index3"),
    vSize="x",
    draw=FALSE
  ) %>>%
  {.$tm} %>>%
  mutate_if(is.factor, as.character) %>>%
  mutate_at(vars(matches("index")),function(x){ifelse(is.na(x),1,x)}) %>>%
  arrange(index1,index2,index3) %>>%
  # much harder dealing with treemap
  #   than data you already have how you like it
  #   this step combines index cols into comma-delimited
  #   so we can apply some logic to get last value
  mutate(name = paste(index1,index2,index3,sep=","))

levelformatter <- formatter(
  "span",
  "class" = ~paste0("level",level),
  # this is the nasty step to get the lowest non-NA index
  #  you can probably ignore this and focus on above class piece
  #  if your data is already in proper format
  ~mapply(function(y,lvl){strsplit(y,",")[[1]][lvl]},name,level)
)

tm %>>%
  select(name,vSize,level) %>>%
  formattable(
    list(
      name = levelformatter,
      # hide level column
      level=FALSE
    )
  ) %>>%
  as.htmlwidget() %>>%
  tags$div(style="width:40%") %>>%
  tagList(
    tags$head(
      tags$style(
"
.level1{font-weight:bold;padding-right:100px;}
.level2{font-style:italic;padding-right:50px;}
.level3{font-size:80%;color:blue}
"
      )
    )
  ) %>>%
  browsable()
@DataStrategist
Copy link

having an error after the first treemap command;

Error in treemap(., index = c("index1", "index2", "index3"), vSize = "x",  : 
  unused argument (draw = FALSE)

@DataStrategist
Copy link

OK, if I remove , draw=FALSE and then add to the top library(formattable) then it works flawlessly. Shall I create another example that starts w/ hirearchichal data already?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment