2013-08-16 2 views
2

Когда я пытаюсь развернуть мой график, ориентированный на силу, следующая полученная ошибка. Я читал об этой проблеме на странице github Майка Бостока и обнаружил, что это может быть связано с значениями NaN координат или всеми точками, нарисованными в одной и той же точке. Я проверил в консоли, и я обнаружил, что все мои очки набираются с одинаковыми значениями X и Y.d3.js Максимальный размер стека вызовов превышен

На примере данных код работал отлично, но не более того. Мои данные идут как 45-50 уровней от центрального узла. Эти данные я успешно выполнил с помощью дерева. Хотел попробовать силовую схему, но это не сработало.

Любая помощь в отношении того, как нарисовать узлы по отдельным координатам, будет очень признательна.

<!DOCTYPE html> 
<meta charset="utf-8"> 
<style> 

.node { 
    stroke: #fff; 
    stroke-width: 1.5px; 
} 

.link { 
    stroke: #999; 
    stroke-opacity: .6; 
} 

</style> 
<body> 
<script src="http://d3js.org/d3.v3.min.js"></script> 
<script> 

var margin = {top: 10, right: 10, bottom: 20, left: 40}, 
    width = 1300 - margin.left - margin.right, 
    height = 800 - margin.top - margin.bottom; 

var color = d3.scale.category20(); 

var force = d3.layout.force().charge(-120) 
      .linkDistance(30) 
      .size([width, height]); 

var svg = d3.select("body").append("svg:svg") 
    .attr("width", width) 
    .attr("height", height) 
    //.attr("pointer-events","all") 
    .append('svg:g') 
    //.call(d3.behavior.zoom().translate([100,50]).scale(.5).on("zoom",redraw)) 
    .append('svg:g') 
    .attr("transform","translate(100,50)scale(.5,.5)"); 

svg.append('svg:rect') 
    .attr('width', width) 
    .attr('height', height) 
    .attr('fill','white') 
    .attr('opacity',0); 

function redraw() { 
    var trans = d3.event.translate; 
    var scale = d3.event.scale; 
    svg.attr("transform", 
     "translate(" + trans + ")" 
     + " scale(" + scale + ")"); 
}; 

d3.json("test_data.json", function(error, graph) { 

    var nodeMap = {}; 
    graph.nodes.forEach(function(x) { nodeMap[x.name] = x; }); 
    graph.links = graph.links.map(
    function(x) 
    { 
    return { 
     source: nodeMap[x.source], 
     target: nodeMap[x.target], 
     value: x.value 
     }; 
    }); 
    console.log(graph.nodes); 
    console.log(graph.links); 
    force 
     .nodes(graph.nodes) 
     .links(graph.links) 
     .start(); 

    var link = svg.selectAll(".link") 
     .data(graph.links) 
     .enter().append("line") 
     .attr("class", "link") 
     .style("stroke", function(d) { return color(d.value); }) 
     .style("stroke-width", function(d) { 
     //console.log(d.value); 
     return Math.sqrt(d.value); }); 

    var node = svg.selectAll(".node") 
     .data(graph.nodes) 

     .enter().append("circle") 
     .attr("class", "node") 
     .attr("r", 5) 
     .style("fill", function(d) { return color(d.value); }) 
     .call(force.drag) 
     .on("mousedown", 
     function(d) { 
      d.fixed = true; 
      d3.select(this).classed("sticky", true); 
     } 
     ) 
     .on("mouseover",fade(0.1)) 
     .on("mouseout",fade(1)); 


    var linkedByIndex = {}; 
    graph.links.forEach(function(d) { 
     linkedByIndex[d.source.index + "," + d.target.index] = 1; 
    }); 

    function isConnected(a, b) { 
     return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index] || a.index == b.index; 
    } 

    node.append("title") 
     .text(function(d) { 
     return "Name : "+d.name+"\n"+"Parent: "+d.parent +"\n"+"Relationship: "+ d.relationship +"\n"+ "Creation Date: "+ d.cod +"\n"; }); 

    function fade(opacity) 
    { 
      return function(d) { 
      node.style("stroke-opacity", function(o) { 
       thisOpacity = isConnected(d, o) ? 1 : opacity; 
       this.setAttribute('fill-opacity', thisOpacity); 
       return thisOpacity; 
      }); 

      link.style("stroke-opacity", opacity).style("stroke-opacity", function(o) { 
       return o.source === d || o.target === d ? 1 : opacity; 
      }); 
     }; 
    } 

force.on("tick", function() { 

    link.attr("x1", function(d) { return d.source.x; }) 
     .attr("y1", function(d) { return d.source.y; }) 
     .attr("x2", function(d) { return d.target.x; }) 
     .attr("y2", function(d) { return d.target.y; }); 

    node 
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); 
    /*node.attr("cx", function(d) { return d.x; }) 
     .attr("cy", function(d) { return d.y; });*/ 
    }); 
}); 

</script> 

JSON выглядит следующим образом:

{ 
    "links": [ 
     { 
      "source": "Me", 
      "target": "Adam", 
      "value": 10 
     }, 
     { 
      "source": "Me", 
      "target": "You", 
      "value": 10 
     } 
    ], "nodes": [ 
      { 
      "ancestor": "Adam", 
      "cod": 19061964, 
      "distance": 0, 
      "name": "Adam", 
      "parent": null, 
      "relationship": null, 
      "value": 10 
     }, 
     { 
      "ancestor": "Adam", 
      "cod": 13032003, 
      "distance": 1, 
      "name": "Me", 
      "parent": "You", 
      "relationship": "Father", 
      "value": 10 
     } 
    ] 
} 

EDIT: я получаю сообщение об ошибке в следующем заявлении:

force 
     .nodes(graph.nodes) 
     .links(graph.links) 
     .start(); 

подсветка:

"start();" 

ответ

-1

В ваших данных ваши ссылки относятся к именам, а не к индексам. Проверьте данные примера с http://bl.ocks.org/mbostock/4062045.

Ссылки имеют форму: {"source":1,"target":0,"value":1}, которая указывает на индекс узла.

+0

Если вы заметили, после строки: d3.json («test_data.json», функция (ошибка, графика) Существует отображение между звеньями и узлами, так что ссылки не должны иметь тот же формат Я заглянул в эту часть ранее. –

+0

Можете ли вы добавить номер ошибки и/или номер, который у вас есть? – david4096

+0

Добавлена ​​строка ошибки и ошибки - это название сообщения –

Смежные вопросы