patition布局

1.partition布局

首先就是先定义一个partition布局还有布局的相关访问函数

var partition=d3.layout.partition()
                        .sort(null)     
                        .size([width,height])
                        .value(function(d){
                            re

json数据格式
这里写图片描述
然后就是加载数据,并用布局包裹数据,得到我们生成图形所需要的特定格式的数据

    var nodes=partition(root);
    var links=partition(nodes);

    console.log(nodes);

这里写图片描述

控制台打印可以看出,每个node有8个字段,children,name,value,depth,x,y,dx(宽度),dy(高度),很好的定义了每个node的属性,有了这些字段便可以生成层层递进的partition布局。

2.全部代码

<style type="text/css">
    .node_text{
        font-size: 15px;
        text-anchor: middle;
    }
</style>
<body>

</body>
<script type="text/javascript">
var width=500,height=500;

var svg=d3.select("body")
            .append("svg")
            .attr("width",width)
            .attr("height",height)
var partition=d3.layout.partition()
                        .sort(null)
                        .size([width,height])
                        .value(function(d){
                            return 1;
                        })
var color=d3.scale.category20();
d3.json("city_tree.json",function(error,root){
    if (error) {
        console.log("load data find error");

    }

    var nodes=partition(root);
    var links=partition(nodes);
    console.log(root)
    console.log(nodes);
    console.log(links);

    var rects=svg.selectAll("g")
                 .data(nodes)
                 .enter()
                 .append("g")
//我们用rect表示层层递进的布局
    rects.append("rect")
        .attr("x",function(d){
            return d.x;
        })
        .attr("y",function(d){
            return d.y;
        })
        .attr("width",function(d){
            return d.dx;
        })
        .attr("height",function(d){
            return d.dy;
        })
        .attr("fill",function(d){
            return color((d.children ? d:d.parent).name);
        })
        .attr("stroke","#fff")
        .on("mouseover",function(d,i){
            d3.select(this)
                .style("fill","yellow");
        })
        .on("mouseout",function(d,i){
            d3.select(this)
                .transition()
                .duration(200)
                .style("fill",function(d){
                    return color((d.children ? d:d.parent).name)
                });
        });

    rects.append("text")
         .attr("transform",function(d){
            return "translate("+(d.x+20)+","+(d.y+20)+")";
         })
         .attr("class","node_text")
         .text(function(d,i){
            return d.name;
         })
})
</script>

这里写图片描述

不足:这篇文章还有很多不足之处,partition的变换形式还没有搞懂,比如说圆形的布局,如果size访问函数设置恰当我们可以生成圆形的布局,看官网例子有些也不太懂,懂得大神可以指点下。

posted @ 2017-10-08 11:03  Braveliberty  阅读(258)  评论(0编辑  收藏  举报