D3是JavaScript的數據可視化庫(http://d3js.org/),參考《數據可視化實戰--使用D3設計交互式圖表》
源碼位於:https://github.com/mbostock/d3/wiki
之前都沒有接觸過庫可以繪製交互圖,初次接觸D3是出於繪製填充樹圖。
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster", "size": 4},
{"name": "CommunityStructure", "size": 2},
{"name": "MergeEdge", "size": 2}
]
}
上述文件是JSON串的形式
遇到的主要問題
1、原數據不是JSON格式,而是Excel格式,Excel可以轉換爲CSV格式,如何實現CSV到JSON。
2、不熟悉d3庫的函數
3、數據的讀取,對象數組的初次使用
一開始想到兩個方案:
1、CSV格式讀入,然後轉換寫入到JSON文件中。數據就可以直接讀取JSON串
2、CSV格式讀入後存儲爲JSON的數據格式,即存到數組中。
CSV 文件:
TYPE
a
b
c
a
d
b
CSV的讀取:1、讀取的CSV數據進行統計 2、CSV的讀取是異步的,因此需要完成的操作都要在函數內部
d3.csv("resources/ff.csv",function(error,csv){
var TypeName=[{}];
var nest=d3.nest()
.key(function(d){return d.TYPE;})
.entries(csv);
for(var i=0;i<nest.length;i++)
{
TypeName[i]={"name":nest[i].key,"size":nest[i].values.length};
}
var root = {"name":"root", "children":[{}]};
TypeName.forEach(function(d){
if(typeof root.children[d.name] !== 'undefined') {
root.children[d.name].children.push(d);
} else {
root.children[d.name] = {"name": d.name, "children": [d]};
}
});
root.children= Object.keys(root.children).map(function (key) { return root.children[key]; });
<pre name="code" class="plain"> div.selectAll(".node")
.data(treemap.nodes(root))//計算樹形佈局和返回節點的數組。
.enter().append("div")
.attr("class", "node")
.style("left", function(d) { return d.x + "px"; })
.style("top", function(d) { return d.y + "px"; })
.style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
.style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; })
.style("background", function(d) { //只爲有孩子的節點賦值,也就是說葉子節點的背景顏色都是他爸爸的顏色
return d.children ? color(d.name) : null;
})
.text(function(d) { //同理,孩子設置文字,爸爸沒有
return d.children ? null : d.name;
});
});
JSON串讀取
d3.json("path/1.json",function(error,json){
console.log(json);
});
總結:
本想存儲JSON文本再讀取,可是寫入文本的代碼。。。腳本里面可以嵌套Java代碼???
JavaScript還很不熟悉呀,簡單的應用花費大量時間,有些地方貌似還是有點問題
可視化之路其慢慢修遠兮~~~~~~~~~暫且這樣吧
參考資料:http://codego.net/570269/
http://blog.csdn.net/tianxuzhang/article/details/17151479