我想用這個JSON表示我的數據作爲使用D3.js.的節點鏈接。我是JavaScript和D3.js的新手。我有3種類型的數據,我想在這3種類型的數據之間建立一個層次結構。家長>源>的孩子,我希望將源上述每一個家長定位和每一位家長鏈接到源,以及每一個孩子應該是源下,並將其鏈接到源:我應該如何格式化我的JSON並向我解釋一些基本的d3圖形節點鏈接?
的script.js
var width = 960,
height = 500;
// i don't really understand what this does
// except the .linkDistance - gives the dimension of the link
var force = d3.layout.force()
.size([width, height])
.charge(-400)
.linkDistance(40)
.on("tick", tick);
// Drag the nodes
var drag = force.drag()
.on("dragstart", dragstart);
//Appends the svg - the place where i draw all my items
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// Select all the links and nodes , from an array ? i don't really get it
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");
// The function where i take the data from the JSON
d3.json("graph.json", function(error, graph) {
if (error) throw error;
force
.nodes(graph.nodes)
.links(graph.links)
.start();
link = link.data(graph.links)
.enter().append("line")
.attr("class", "link");
node = node.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 12)
.on("dblclick", dblclick)
.call(drag);
});
// Here is the function where i should asign the position of the nodes and the links
// This is the most problematic and i really don't understand it
function tick(){}
// The function to fix and to clear the fix from a node
function dblclick(d) {
d3.select(this).classed("fixed", d.fixed = false);
}
function dragstart(d) {
d3.select(this).classed("fixed", d.fixed = true);
}
的Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
<title>D3 Test</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="script.js"></script>
</head>
</body>
的style.css
.link {
stroke: #777;
stroke-width: 2px;
}
.nodes circle{
cursor: move;
fill: #ccc;
stroke: #000;
stroke-width: 1.5px;
}
.node.fixed {
fill: #f00;
}
graph.json
{
"nodes":[
{
"id": "Source" , "group" :0
},
{
"id":"Parent_1" , "group" : 1
},
{
"id": "Parent_2" , "group" :1
},
{
"id": "Parent_3" , "group" :1
},
{
"id":"Child_1" , "group":2
},
{
"id":"Child_2" , "group":2
},
{
"id":"Child_3" , "group":2}
],
"links":[
{
"source":"Source","target":"Parent_1"
},
{
"source":"Source","target":"Parent_2"
},
{
"source":"Source","target":"Parent_3"
},
{
"source":"Source","target":"Child_1"
},
{
"source":"Source","target":"Child_2"
},
{
"source":"Source","target":"Child_3"
},
]
}
如果有人解釋我如何格式化我的JSON,所以我可以更多的使用它的時間和心情有效地解釋我如何使用d3逐步創建節點鏈接圖或給我一個演示並解釋每一塊代碼,我將非常感謝。 如果我提出問題的方式有問題,或者有什麼不清楚的地方,請說出來我可以編輯它。謝謝 !
這是一個相當大的問題,需要解釋很多工作。你的Json在我看來很好,因爲它的格式正確並提供了鏈接(將每個孩子和父母鏈接到「源」)。您當然可以使用武力在SVG中將父母/孩子分組在一起。你讀過https://www.dashingd3js.com/和http://d3indepth.com/about/。如果你設置了一個gist/block,jsfiddle或者plunkr,那麼你可以測試你的代碼,並且人們可以看到錯誤。 –
是的,我一直在尋找很多教程和解釋代碼,但我仍然不明白,謝謝你,但我會檢查免費視頻的鏈接。 –