2014-02-09 53 views
2

我是一名javascript/d3初學者,遇到了一個很棒的network visualization我想玩一玩。迭代地將鏈接附加到D3強制定向的網絡可視化

我期望通過在指定時間添加鏈接及其關聯節點來使動畫可視化。

爲了讓我開始,我首先嚐試保持所有節點顯示,並簡單地添加鏈接,因爲它們出現在數據文件中。

剝離下來的original html文件,這裏是我的嘗試(添加iterateLink()函數,並略微調整initializeGraph()):

function iterateLinks() { 
    for (x = 0; x < zlinkz.length; x++) { 
    setTimeout(function() { 

     links.push(zlinkz[x]); 
     restart(); 
    }, 2000); 
    } 
} 

function initializeGraph(newGraph) { 
    newNodes = []; 
    newLinks = []; 
    // We need a hash to fit the link structure of D3's force-directed layout 
    nodeHash = {}; 

    zlinkz = []; 

    for (x = 0; x < newGraph.nodes.length; x++) { 
    newNodes.push(newGraph.nodes[x]); 
    nodeHash[String(newGraph.nodes[x].id)] = x; 
    } 

    for (x = 0; x < newGraph.links.length; x++) { 
    newLinks.push({id: x, source: newGraph.nodes[nodeHash[newGraph.links[x].source]], target: newGraph.nodes[nodeHash[newGraph.links[x].target]], "cost": newGraph.links[x].cost, "weight": newGraph.links[x].invcost }); 
    } 

    force = d3.layout.force() 
     .size([width, height]) 
     .nodes(newNodes) // initialize with a single node 
     .links(newLinks) 
     .linkDistance(60) 
     .charge(-60) 
     .on("tick", tick); 

    var svg = d3.select("#viz").append("svg") 
     .attr("width", width) 
     .attr("height", height) 
     .attr("id", "networkViz"); 

    svg.append("rect") 
     .attr("width", width) 
     .attr("height", height) 
     .attr("id","backgroundRect") 
     .on("mousemove", mousemove); 

    nodes = force.nodes(); 
    links = force.links(); 
    node = svg.selectAll(".node"); 
    link = svg.selectAll(".link"); 
    arrowhead = svg.selectAll(".link"); 

    cursor = svg.append("circle") 
     .attr("transform", "translate(-100,-100)") 
     .attr("class", "cursor") 
     .attr("r", 1) 
     .style("opacity", 0); 

    restart(); 
    iterateLinks(); 
} 

完整的代碼可以在jsfiddle找到。

儘管我的iterateLinks()函數並沒有顯示鏈接,但該函數似乎無法遍歷鏈接。

你知道我在哪裏出錯了,如何解決它?

任何幫助非常感謝! 謝謝。

=====編輯=====

感謝@Barnab和@ AmeliaBR的幫助下,我所做的更改here,也包括增加節點動態了。

回答

3

幾件事情:

  • 在你的iterateLinks可變x從0到2中setTimeout函數被調用,從而導致推動總是zlinkz[3]而不是你所需的範圍0至2.我固定之前這種方式和它的作品,你可能它想要的方式:

    var it = 0; 
    for (x = 0; x < zlinkz.length; x++) { 
        setTimeout(function() { 
         links.push(zlinkz[it]); 
         restart(); 
         it++; 
        }, 2000); 
    } 
    
  • 好像有什麼問題你arrowhead圖。我在這個更新的jsfiddle中評論過它,如果我理解它的功能是什麼,我可能會幫助你調試它:)如果取消註釋它,你會看到你的鏈接和節點因爲有問題而消失.getElementById('directedCheck').checked

PS:我已經寫了一篇關於my blog的動態力佈局可視化的教程,也許它可以給你一些未來的嘗試。

+2

此外,您可能打算讓每個鏈接單獨添加;要做到這一點,使你的setTimeout時間參數爲'2000 * x'(注意,在這種情況下,x將在計時器啓動時計算,而不是在執行該函數時計算,因此每次輪換'for'循環)。你也可以用'setInterval'稍微更有效地做同樣的事情,請參閱http://jsfiddle.net/28q4G/7/ – AmeliaBR

+0

感謝@Barnab和@AmeliaBR!我做了你推薦的更改(參見http://jsfiddle.net/28q4G/11/),並使節點動態顯示,但可視化效果非常不穩定。你知道這是爲什麼嗎?我非常感謝你的幫助! – zanbri

+0

我發現這是因爲我重複添加了相同的節點。變化在這裏:http://jsfiddle.net/28q4G/12/ – zanbri