2017-12-03 13 views
0

최신 코드 시도 :Bounded Force Layout (D3 v4)에 노드 레이블을 추가하는 방법은 무엇입니까?

var node = svg.selectAll("circle") 
     .data(graph.nodes) 
    .enter().append("circle") 
     .attr("r", radius - .75) 
     .style("fill", function(d) { return fill(d.group); }) 
     .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); }) 
     .call(force.drag); 

    var label = svg.selectAll("text") 
    .data(graph.nodes) 
    .enter() 
    .append("text") 
    .text(function(d){return d.id; }); 
    .style("text-anchor", "middle") 
    .attr("font-family", "sans-serif") 
    .attr("font-size", "11px") 
    .attr("fill", "red"); 
}) 

    force 
     .nodes(graph.nodes) 
     .links(graph.links) 
     .on("tick", tick) 
     .start(); 

    function tick() { 
    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); }) 
     .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); }); 

    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; }); 

    label.attr("x", function(d){ return d.x; }) 
      .attr("y", function (d) {return d.y }); 

안녕 모두,

내가 D3에 초보자이고 아무 소용 지금까지이 문제에 거의 2 일을 보내왔다!

내가 https://bl.ocks.org/mbostock/1129492

의 버전으로 노드 레이블을 추가하려고 I했습니다 복사/나는 모든 포럼 응답에서 코드를 붙여 조각을 찾을 수 있으며 하나 내 다이어그램 (실행에 빈 화면)을 중단 또는이 효과 없음 (꽤 많은 색의 서클이 있지만 레이블이 없음). 다른 강제 다이어그램에 레이블을 성공적으로 추가 할 수 있었지만 그 중 하나는 제한되지 않았으며 경계는 내가 갖고 싶은 핵심 기능입니다. 이 단계에서는 graph.json 파일을 변경하지 않았습니다. Bostock이 설정했습니다. 나는 단순히 노드 텍스트 레이블을 표시하려고 노력하고있다.

레이블을 표시하기 위해 작성해야하는 코드와 위치 및 삽입 방법을 알려주실 수 있습니까? 나는이 것을 포기하지 않기로 결정했습니다! 나는 다음을 수행하여 각 노드의 레이블을 포함하도록 example from Mike Bostock을 수정 한

<!DOCTYPE html> 
 
<meta charset="utf-8"> 
 
<style> 
 
circle { 
 
    stroke-width: 1.5px; 
 
} 
 
line { 
 
    stroke: #999; 
 
} 
 
text { 
 
    font: 12px "open sans"; 
 
    fill: #fff; 
 
} 
 

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

 
var width = 960, 
 
    height = 500, 
 
    radius = 6; 
 

 
var fill = d3.scaleOrdinal() 
 
.range(["#a02a65","#2aa02a","#2aa0a0","#a0652a","#a02a2a","#2a2aa0","#65a02a","#a0a02a"]) 
 

 
var simulation = d3.forceSimulation() 
 
    .velocityDecay(0.1) 
 
    .force("x", d3.forceX(width/2).strength(.05)) 
 
    .force("y", d3.forceY(height/2).strength(.05)) 
 
    .force("charge", d3.forceManyBody().strength(-240)) 
 
    .force("link", d3.forceLink().distance(50).strength(1)); 
 

 
var svg = d3.select("body").append("svg") 
 
    .attr("width", width) 
 
    .attr("height", height); 
 

 
d3.json("https://[URL HERE]/graph.json", function(error, graph) { 
 
    if (error) throw error; 
 

 
var link = svg.selectAll("line") 
 
     .data(graph.links) 
 
    .enter().append("line"); 
 
    var node = svg.selectAll("circle") 
 
     .data(graph.nodes) 
 
    .enter().append("circle") 
 
     .attr("r", radius - .75) 
 
     .style("fill", function(d) { return fill(d.group); }) 
 
     .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); }) 
 
     .call(d3.drag() 
 
      .on("start", dragstarted) 
 
      .on("drag", dragged) 
 
      .on("end", dragended)); 
 
    
 
    var labels = node.append("text") 
 
     .text(function(d) { 
 
     return d.id; 
 
     }) 
 
     .attr('x', 6) 
 
     .attr('y', 3); 
 
    
 
    node.append("title") 
 
     .text(function(d) { return d.id; });simulation 
 
     .nodes(graph.nodes) 
 
     .on("tick", tick); 
 
    simulation.force('link') 
 
     .links(graph.links); 
 
    function tick() { 
 
    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); }) 
 
     .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); }); 
 
    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; }); 
 
    } 
 
}); 
 
function dragstarted(d) { 
 
    if (!d3.event.active) simulation.alphaTarget(0.3).restart(); 
 
    d.fx = d.x; 
 
    d.fy = d.y; 
 
} 
 
function dragged(d) { 
 
    d.fx = d3.event.x; 
 
    d.fy = d3.event.y; 
 
} 
 
function dragended(d) { 
 
    if (!d3.event.active) simulation.alphaTarget(0); 
 
    d.fx = null; 
 
    d.fy = null; 
 
} 
 
</script>

+0

변수 노드 타이틀 원 요소의 선택으로 나타나지만 제목은 일반적으로 렌더링하지/요소/제목). 서클 데이터 조인을 반복하지만 텍스트 요소를 원하거나 각 노드의 그룹 요소를 만든 다음 원과 레이블을 추가 할 수 있습니다. – John

+0

안녕하세요 John! 응답 해 주셔서 너무 감사드립니다. 위대한 모든 소리지만 당신이 코드 현명한 제안을 구현하는 방법을 모르겠다.코드 스 니펫/s로 올바른 방향으로 나를 가리킬 수있는 기회가 있습니까? 다시 한 번 감사드립니다 !! – workinitout

+0

이 답변을보십시오 : https://stackoverflow.com/a/37640083/7106086 –

답변

0

: 여기

내 코드의 각 노드에 대해

  1. 라벨입니다 graph.nodes에서 먼저 선택 labels을 만듭니다. 일반적인 d3 데이터 조인을 수행하여 텍스트 요소를 추가하고 레이블 텍스트를 설정하십시오.

  2. 레이블의 위치는 tick() 함수에서 발생합니다. 애니메이션의 각 단계에서 에 graph.node요소의 x 및 y 값에 따라 텍스트 요소의 xy 속성을 설정합니다. 자세한 내용은 here를 찾을 수 등 규모에 사용되는 주로 이름 -

구문에 약간의 변화가있을 것이다, 그래서이 예제는 D3의 V3를 사용하고 있습니다.

중복을 피하기 위해 텍스트의 위치를 ​​지정하지 않았습니다. 이것은 합리적으로 관련되어 있으며 this other SO post과 같은 다른 곳에서 논의됩니다. (https://developer.mozilla.org/en-US/docs/Web/SVG

var width = 960, 
 
    height = 500, 
 
    radius = 6; 
 
    
 
var fill = d3.scale.category20(); 
 

 
var force = d3.layout.force() 
 
    .gravity(.05) 
 
    .charge(-240) 
 
    .linkDistance(50) 
 
    .size([width, height]); 
 
    
 
var svg = d3.select("body").append("svg") 
 
    .attr("width", width) 
 
    .attr("height", height); 
 
    
 
d3.json("https://gist.githubusercontent.com/mbostock/1129492/raw/9513c3fe193673a09e161d49d00a587fd806bdf5/graph.json", function(error, graph) { 
 
    if (error) throw error; 
 
    
 
    var link = svg.selectAll("line") 
 
     .data(graph.links) 
 
    .enter().append("line"); 
 
    
 
    var node = svg.selectAll("circle") 
 
     .data(graph.nodes) 
 
    .enter().append("circle") 
 
     .attr("r", radius - .75) 
 
     .style("fill", function(d) { return fill(d.group); }) 
 
     .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); }) 
 
     .call(force.drag); 
 
    
 
    var labels = svg.selectAll("text") 
 
     .data(graph.nodes) 
 
    .enter().append('text') 
 
     .text(function (d){return d.name}); 
 
     
 
    force 
 
     .nodes(graph.nodes) 
 
     .links(graph.links) 
 
     .on("tick", tick) 
 
     .start(); 
 
     
 
    function tick() { 
 
    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); }) 
 
     .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); }); 
 
     
 
    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; }); 
 
    
 
    labels.attr('x', function(d) { return d.x; }) 
 
      .attr('y', function(d) { return d.y; }); 
 
    } 
 
});
circle { 
 
    stroke-width: 1.5px; 
 
} 
 
line { 
 
    stroke: #999; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

+0

안녕하세요. 고맙습니다!!! 나는 내일 이것에 집착 할 것이다. 내가 어떻게하는지 알려줄거야. 에이미. – workinitout