【D3.js 学习总结】18、D3布局-分区图(圆形)

    xiaoxiao2026-04-06  8

    d3.layout.partition()

    上节中展示的是基本的方形分区图,这节我们要做一个圆形的分区图,圆形图跟方形图基本相同,只有布局函数的 size 函数和绘制图形的部分稍有区别;

    1、数据

    var dataset = { "name": "中国", "children": [ { "name": "浙江", "children": [ {"name":"嘉兴", "gdp":3147}, {"name":"金华", "gdp":2958}, {"name":"衢州", "gdp":1056} ] }, { "name": "广东", "children": [ {"name":"杭州", "gdp":8343}, {"name":"绍兴", "gdp":3620}, {"name":"湖州", "gdp":1803} ] }, { "name": "福建", "children": [ {"name":"舟山", "gdp":1021}, {"name":"台州", "gdp":3153}, {"name":"丽水", "gdp":983} ] } ] }

    2、数据转换

    var width = 500; var height = 500; var radius = Math.min(width, height) / 2 var partition = d3.layout.partition() .sort(null) //设定内部的顶点的排序函数,null 表示不排序 .size([2 * Math.PI, radius * radius]) //第一个值为 2 * PI ,第二个值为圆半径的平方,暂时不去深究为什么这么做,只需记得这么用即可 .value(function(d) { return d.gdp; }); //设定表示分区大小的值 var nodes = partition.nodes(dataset); var links = partition.links(nodes);

    转换数据后,节点数组的输出结果如图所示。

    其中,节点对象的属性包括:

    x: 绕圆心方向的起始位置y: 由圆心向外方向的结束位置dx: 起始位置宽度dy: 结束位置宽度

    本例中将不会用到liks数据对象;

    3、绘制图形

    生成SVG容器

    var svg = d3.select('body').append('svg') .attr('class','axis') .attr('width',width) .attr('height',height) .append('g') .attr("transform", "translate(" + radius + "," + radius + ")");

    生成颜色比例尺

    var color = d3.scale.category20();

    创建圆弧SVG生成器

    var arc = d3.svg.arc() .startAngle(function(d) { return d.x; }) .endAngle(function(d) { return d.x + d.dx; }) .innerRadius(function(d) { return Math.sqrt(d.y); }) .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });

    为节点数据创建容器

    var arcs = svg.selectAll("g") .data(nodes) .enter().append("g");

    为节点数据创建圆弧路径

    arcs.append("path") .attr("d", arc) .style("stroke", "#fff") .style("fill", function(d) { return color(d.name); })

    生成文本

    arcs.append("text") .attr("text-anchor","middle") .attr("transform",function(d,i){ //第一个元素不动 if( i == 0 ) return ; //其它的平移 return "translate(" + arc.centroid(d) + ")" }) .text(function(d) { return d.name; });

    查看在线演示

    相关资源:基于D3js布局显示树的Vue组件
    最新回复(0)