Tidy tree diagram , icicle diagram and sunburst diagram

data

绘制树图以及接下来两种图形都需要层次化结构的数据,所以首先的操作就是将数组类型的元素重组为层次结构数据,这里用到了d3.nest(),返回的结果是一个嵌套的数组,最外层数据都是由键值对组成,还可以通过nest.rollup()归纳函数统计叶子节点的数目。

Tidy tree diagram

屏幕快照 2018-11-18 下午5.19.50.png

屏幕快照 2018-11-18 下午5.21.08.png

树图的绘制包括连线和节点的绘制两个部分。
首先是数据的处理,层次结构数据由上述方法得到之后,在经过d3.hierarchy()添加上父节点、子节点、高度、深度等,d3.tree()定义tree层级,并加上节点的x、y坐标。
连线的path生成是采用了d3.linkHorizontal(),绑定的数据是link.links(),返回的是带有sourcetarget属性的对象数组。
节点的绘制绑定的数据是node.descendants(),返回后代节点数组,第一个节点是自身,然后依次为所有子节点的拓扑排序。

//关键部分代码
function tree(data){
        var root = d3.hierarchy(data);//计算父节点 子节点 高度和深度
        root.dx = 10-textelementx.length; //第一个元素的初始位置
        root.dy = width/(root.height+1);
        return d3.tree().nodeSize([root.dx,root.dy])(root);// 定义tree层级,设置宽高
    }
    let x0 = Infinity;
    let x1 = -x0;
    root.each(d=>{
        if(d.x>x1)x1=d.x;
        if(d.x<x0)x0=d.x;
    })
    var svg = d3.select("#chart")
        .append("svg")
        .attr("width",width)
        .attr("height",500)
        .attr("overflow","visible");
    var g = svg.append("g")
        .attr("font-family","sans-serif")
        .attr("font-size",10)
        .attr("transform",`translate(${root.dy/3},${root.dx-x0})`);
    var link = g.append("g")
        .attr("fill","none")
        .attr("stroke","#555")
        .attr("stroke-opacity",0.4)
        .attr("stroke-width",1.5)
        .selectAll("path")
        .data(root.links())
        .enter().append("path")
        .attr("d",d3.linkHorizontal()
            .x(d=>d.y)
            .y(d=>d.x));
    const node = g.append("g")
        .attr("stroken-linejoin","round")
        .attr("stroke-width",3)
        .selectAll("g")
        .data(root.descendants().reverse())
        .enter().append("g")
        .attr("transform",d=>`translate(${d.y},${d.x})`);
    node.append("circle")
        .attr("fill",d => d.children?"#555":"#999")
        .attr("r",2.5);
    node.append("text")
        .attr("dy", "0.31em")
        .attr("x", d => d.children? -6 : 6)
        .attr("text-anchor", d => d.children? "end" : "start")
        .text(function(d){
            return d.data.name;
        })
        .clone(true).lower()
        .attr("stroke", "white");

icicle diagram

屏幕快照 2018-11-18 下午7.55.35.png

屏幕快照 2018-11-18 下午7.56.34.png

绘制方式与tidy tree大致相同,将节点的圆形改为矩形框,而且不用画之间的连线。

//部分关键代码
var partition = data=> 
        d3.partition()
        .size([height,width])
        .padding(1)
        (d3.hierarchy(data)
        .sum(d=>d.value)
        );
    
    var color = d3.scaleOrdinal().range(d3.quantize(d3.interpolateRainbow,dataobj.values.length+1))
    var format = d3.format(",d")
    var root = partition(json2);
    var svg = d3.select("#chart")
        .append("svg")
        .attr("width",width)
        .attr("height",height)
        .attr("font-size","10")
        .attr("font-family","sans-serif");
    var cell = svg.selectAll("g")
        .data(root.descendants())
        .enter().append("g")
        .attr("transform",d=>`translate(${d.y0},${d.x0})`);
    cell.append("rect")
        .attr("width",d => d.y1-d.y0)
        .attr("height",d => d.x1-d.x0)
        .attr("fill-opacity",0.6)
        .attr("fill",d => {
            if(!d.depth)return "#ccc";
            while(d.depth>1)d=d.parent;
            return color(d.data.name);
        });
    var text = cell.filter(d =>(d.x1-d.x0)>16).append("text")
        .attr("x",4)
        .attr("y",13);
    text.append("tspan")
        .text(function(d){
            return d.data.name;
        });
    text.append("tspan")
        .attr("fill-opacity",0.7)
        .text(d=>`${format(d.value)}`);
    cell.append("title")
        .text(d=>`${d.ancestors().map(d=>d.data.name).reverse().join("/")}\n${format(d.value)}`);

sunburst diagram

屏幕快照 2018-11-18 下午8.02.33.png

Zoomable sunburst 是一个可以进行缩放操作的展示变量之间的层次结构和比例的图表,就我看来,相对之前的两种表示结构层次的树状图,这种图表比较清晰,也能利用有限的空间来展示节点层次比较深的结构,节点之间的比例关系也展示了出来。
操作:选择要展示的变量,就可以画出按所添加变量的顺序为基础的结构层次的环形图,点击环形图的各个块,如果该块有子元素,就将子元素显示出来,点击中间的空白的白色圆就会返回上一层元素结构。
圆环的绘制采用的和饼图绘制采用的方法大致相同,都是采用弧生成器生成扇形,但是只是显示想要的部分,另外的部分暂时将其透明度设置为0,点击之后再设置坐标,然后在将其透明度设置为非零。

//部分关键代码
var arc = d3.arc()
    .startAngle(d => d.x0)
    .endAngle(d => d.x1)
    .padAngle(d => Math.min((d.x1 - d.x0) / 2, 0.005))
    .padRadius(radius * 1.5)
    .innerRadius(d => d.y0 * radius)
    .outerRadius(d => Math.max(d.y0 * radius, d.y1 * radius - 1));
    const root = partition(json2);

    root.each(d => d.current = d);

    const svg = d3.select("#chart")
        .append("svg")
        .attr("width",width)
        .attr("height",height)
        .style("font", "10px sans-serif");

    const g = svg.append("g")
        .attr("transform", `translate(${width / 2},${width / 2})`);

    const path = g.append("g")
        .selectAll("path")
        .data(root.descendants().slice(1))
        .enter().append("path")
        .attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); })
        .attr("fill-opacity", d => arcVisible(d.current) ? (d.children ? 0.6 : 0.4) : 0)
        .attr("d", d => arc(d.current));

    path.filter(d => d.children)
        .style("cursor", "pointer")
        .on("click", clicked);

    path.append("title")
        .text(d => `${d.ancestors().map(d => d.data.name).reverse().join("/")}\n${format(d.value)}`);

    const label = g.append("g")
        .attr("pointer-events", "none")
        .attr("text-anchor", "middle")
        .style("user-select", "none")
        .selectAll("text")
        .data(root.descendants().slice(1))
        .enter().append("text")
        .attr("dy", "0.35em")
        .attr("fill-opacity", d => +labelVisible(d.current))
        .attr("transform", d => labelTransform(d.current))
        .text(d => d.data.name);

    const parent = g.append("circle")
        .datum(root)
        .attr("r", radius)
        .attr("fill", "none")
        .attr("pointer-events", "all")
        .on("click", clicked);

    function clicked(p) {
        parent.datum(p.parent || root);

        root.each(d => d.target = {
        x0: Math.max(0, Math.min(1, (d.x0 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
        x1: Math.max(0, Math.min(1, (d.x1 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
        y0: Math.max(0, d.y0 - p.depth),
        y1: Math.max(0, d.y1 - p.depth)
        });

        const t = g.transition().duration(750);

        // Transition the data on all arcs, even the ones that aren’t visible,
        // so that if this transition is interrupted, entering arcs will start
        // the next transition from the desired position.
        path.transition(t)
            .tween("data", d => {
            const i = d3.interpolate(d.current, d.target);
            return t => d.current = i(t);
            })
        .filter(function(d) {
            return +this.getAttribute("fill-opacity") || arcVisible(d.target);
        })
            .attr("fill-opacity", d => arcVisible(d.target) ? (d.children ? 0.6 : 0.4) : 0)
            .attrTween("d", d => () => arc(d.current));

        label.filter(function(d) {
            return +this.getAttribute("fill-opacity") || labelVisible(d.target);
        }).transition(t)
            .attr("fill-opacity", d => +labelVisible(d.target))
            .attrTween("transform", d => () => labelTransform(d.current));
  }
  
  function arcVisible(d) {
    return d.y1 <= 3 && d.y0 >= 1 && d.x1 > d.x0;
  }

  function labelVisible(d) {
    return d.y1 <= 3 && d.y0 >= 1 && (d.y1 - d.y0) * (d.x1 - d.x0) > 0.03;
  }

  function labelTransform(d) {
    const x = (d.x0 + d.x1) / 2 * 180 / Math.PI;
    const y = (d.y0 + d.y1) / 2 * radius;
    return `rotate(${x - 90}) translate(${y},0) rotate(${x < 180 ? 0 : 180})`;
  }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,176评论 5 469
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,190评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,232评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,953评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,879评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,177评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,626评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,295评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,436评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,365评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,414评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,096评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,685评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,771评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,987评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,438评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,032评论 2 341

推荐阅读更多精彩内容