分區圖布局的 size 函數很有意思,即可用于制作矩形分區圖,也可用于制作圓形分區圖。本文就來談討一下圓形分區圖的制作。
[](http://www.ourd3js.com/wordpress/wp-content/uploads/2014/11/311.png)
本文與【[進階 - 第 3.0 章](http://www.ourd3js.com/wordpress/?p=643)】基本相同,只有布局函數的 size 函數和繪制圖形的部分稍有區別。
## 1. 數據
本文仍然使用【[入門 - 第 9.4 章](http://www.ourd3js.com/wordpress/?p=254)】的數據,內容為中國境內幾個城市的所屬關系。
## 2. 布局(數據轉換)
~~~
var partition = d3.layout.partition()
.sort(null)
.size([2 * Math.PI, radius * radius])
.value(function(d) { return 1; });
~~~
第 3 行:size 函數,第一個值為 2 * PI ,第二個值為圓半徑的平方。如果您只需要得到效果,可不比深究為什么這么做,只需記得這么用即可。
注意第3行與【[進階 - 第 3.0 章](http://www.ourd3js.com/wordpress/?p=643)】的不同。
## 3. 繪制
先定義一個繪制弧形的函數,這個函數在【[入門 - 第 9.1 章](http://www.ourd3js.com/wordpress/?p=190)】中也用過。
~~~
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); });
~~~
請好好體會上面的代碼是什么意思。如果以圓形的形式來轉換數據,那么 d.x 和 d.y 分別代表圓弧的繞圓心方向的起始位置和由圓心向外方向的其實位置。d.dx 和 d.dy 分別代表各自的寬度。
接下來分別繪制圓弧和文字。
~~~
var arcs = svg.selectAll("g")
.data(nodes)
.enter().append("g");
arcs.append("path")
.attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color((d.children ? d : d.parent).name); })
.on("mouseover",function(d){
d3.select(this)
.style("fill","yellow");
})
.on("mouseout",function(d){
d3.select(this)
.transition()
.duration(200)
.style("fill", function(d) {
return color((d.children ? d : d.parent).name);
});
});
arcs.append("text")
.style("font-size", "12px")
.style("font-family", "simsun")
.attr("text-anchor","middle")
.attr("transform",function(d,i){
//第一個元素(最中間的),只平移不旋轉
if( i == 0 )
return "translate(" + arc.centroid(d) + ")";
//其他的元素,既平移也旋轉
var r = 0;
if( (d.x+d.dx/2)/Math.PI*180 < 180 ) // 0 - 180 度以內的
r = 180 * ((d.x + d.dx / 2 - Math.PI / 2) / Math.PI);
else // 180 - 360 度以內的
r = 180 * ((d.x + d.dx / 2 + Math.PI / 2) / Math.PI);
//既平移也旋轉
return "translate(" + arc.centroid(d) + ")" +
"rotate(" + r + ")";
})
.text(function(d) { return d.name; });
~~~
繪制方法問題不大,唯一要注意的是文字的旋轉角度問題,請好好看看上面的注釋問題。
## 4. 結果
完整代碼,請點擊下面的鏈接,再右鍵點擊查看源代碼:
[http://www.ourd3js.com/demo/J-3.1/circle_partition.html](http://www.ourd3js.com/demo/J-3.1/circle_partition.html)
### 文檔信息
- 版權聲明:署名(BY)-非商業性(NC)-禁止演繹(ND)
- 發表日期:2014 年 11 月 30?日
- 更多內容:[OUR D3.JS - 數據可視化專題站](http://www.ourd3js.com/) 和 [CSDN個人博客](http://blog.csdn.net/lzhlzz)
- 備注:本文發表于 [OUR D3.JS](http://www.ourd3js.com/) ,轉載請注明出處,謝謝