A hierarchy tree presentation of the classic Titanic
R dataset.
Charts are tree and sunburst, with morphing animation between them.
Coding is in R using library echarty which is based on
Javascript library ECharts. Charts are
interactive - tooltips, zoom, pan, click, etc.
A detailed study of hierarchical data and charting could be found in this
article.
# JS code for the switch button
jswitch= "function(event) {
chart = get_e_charts(echwid);
opt= chart.getOption();
keep= opt.morph;
for(i=0; i<keep.length; i++) {
if (opt.series[0].type==keep[i].series[0].type) {
next= (i+1) % keep.length;
optcurr= Object.assign({}, keep[next]);
break;
}
};
if (!optcurr) return;
optcurr.morph= keep;
chart.setOption(optcurr);
}"
library(dplyr)
# build required pathString and optional itemStyle columns
df <- as.data.frame(Titanic) |> rename(value= Freq) |>
mutate(
pathString= paste('Titanic\nSurvival', Survived, Age, Sex, Class, sep='/'),
itemStyle= case_when(Survived=='Yes' ~ "color='green'",
TRUE ~ "color='LightSalmon'")) |>
select(pathString, value, itemStyle)
library(echarty) # v.1.6.0.01+
dat <- ec.data(df, format='treeTK')
dat[[1]]$itemStyle <- list(color= 'lightgray') # customize top
dat[[1]]$pct <- 100
p1 <- ec.init(preset= FALSE,
tooltip= list(formatter= ec.clmn('%@<br>%@%','value','pct')),
graphic= list(
ec.util(cmd='button', text='switch', right=35, top=20, js=jswitch)),
series= list(list(
data= dat,
type= 'sunburst', radius= c(0, '85%'), label= list(rotate=0),
labelLayout= list(hideOverlap= TRUE),
universalTransition= list(enabled= TRUE),
emphasis= list(focus='none')
))
)
p2 <- p1 |> ec.upd({
series[[1]] <- within(series[[1]], {
type <- 'tree'; roam <- T; symbol= 'circle'; initialTreeDepth= 3;
symbolSize <- ec.clmn("(x) => {return Math.max(Math.log(x)*10, 0.5)}")
lineStyle <- list(width= 3)
itemStyle <- list(borderWidth= 2, borderColor='#ccc')
})
})
ec.util(cmd='morph', p2,p1, js=FALSE) |> ec.theme('dark-mushroom')