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訪問函數設置恰當我們可以生成圓形的佈局,看官網例子有些也不太懂,懂得大神可以指點下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章