web-dev-qa-db-ja.com

d3 Nodeラベリング

this d3 project のサンプルコードを使用して、d3グラフの表示方法を学びましたが、円の中央にテキストが表示されないようです( この例 および この例 )。私は他の例を見て、追加しようとしました

node.append("title").text("Node Name To Display")

そして

node.append("text")
    .attr("text-anchor", "middle")
    .attr("dy", ".3em").text("Node Name To Display")

ノードが定義された直後に表示される結果は、各ノードにカーソルを合わせると「表示するノード名」が表示されるだけです。円の中にテキストとして表示されません。独自のsvgテキストオブジェクトを作成し、円の半径の座標に基づいて配置する必要がある座標を決定する必要がありますか?他の2つの例から、d3はすでに何らかの形でこれを処理しているように見えます。呼び出し/設定する適切な属性がわからないだけです。

46
Josh Bradley

多くの例 グラフとツリーの視覚化にラベルを追加する方法を示していますが、おそらくこれを最も簡単なものから始めるでしょう:

コードへのリンクを投稿していませんが、nodeはSVGサークル要素の選択を指していると推測しています。 circle要素は containersではないため、text要素をcircle要素に追加することはできません。テキスト要素を円に追加しても無視されます。

通常、G要素を使用して、サークル要素(または上記の画像要素)と各ノードのテキスト要素をグループ化します。結果の構造は次のようになります。

<g class="node" transform="translate(130,492)">
  <circle r="4.5"/>
  <text dx="12" dy=".35em">Gavroche</text>
</g>

data-join を使用して各ノードのG要素を作成し、次に selection.append を使用してそれぞれに円とテキスト要素を追加します。このようなもの:

var node = svg.selectAll(".node")
    .data(nodes)
  .enter().append("g")
    .attr("class", "node")
    .call(force.drag);

node.append("circle")
    .attr("r", 4.5);

node.append("text")
    .attr("dx", 12)
    .attr("dy", ".35em")
    .text(function(d) { return d.name });

このアプローチの欠点の1つは、円の上にラベルを描画する必要がある場合があることです。 SVGはまだz-indexをサポートしていないため、要素はドキュメント順に描画されます。したがって、上記のアプローチでは、ラベルが描画されます円の上ですが、描画される場合があります他の円の下。これを修正するには、次のように2つのデータ結合を使用し、円とラベルに個別のグループを作成します。

<g class="nodes">
  <circle transform="translate(130,492)" r="4.5"/>
  <circle transform="translate(110,249)" r="4.5"/>
  …
</g>
<g class="labels">
  <text transform="translate(130,492)" dx="12" dy=".35em">Gavroche</text>
  <text transform="translate(110,249)" dx="12" dy=".35em">Valjean</text>
  …
</g>

そして、対応するJavaScript:

var circle = svg.append("g")
    .attr("class", "nodes")
  .selectAll("circle")
    .data(nodes)
  .enter().append("circle")
    .attr("r", 4.5)
    .call(force.drag);

var text = svg.append("g")
    .attr("class", "labels")
  .selectAll("text")
    .data(nodes)
  .enter().append("text")
    .attr("dx", 12)
    .attr("dy", ".35em")
    .text(function(d) { return d.name });

この手法は、 Mobile Patent Suits の例で使用されています(白い影を作成するために追加のテキスト要素が使用されています)。

86
mbostock

大きなラベルに合わせてノードを拡大する場合は、SVGテキストノードのgetBBoxプロパティを描画後に使用できます。固定座標と2つの可能な形状を持つノードのリストに対して、私がそれをどのように行ったかを以下に示します。

nodes.forEach(function(v) {
  var nd;
  var cx = v.coord[0];
  var cy = v.coord[1];

  switch (v.shape) {
    case "circle":
      nd = svg.append("circle");
      break;
    case "rectangle":
      nd = svg.append("rect");
      break;
  }

  var w = 10;
  var h = 10;
  if (v.label != "") {
    var lText = svg.append("text");

    lText.attr("x", cx)
         .attr("y", cy + 5)
         .attr("class", "labelText")
         .text(v.label);

    var bbox = lText.node().getBBox();
    w = Math.max(w,bbox.width);
    h = Math.max(h,bbox.height);
  }

  var pad = 4;

  switch (v.shape) {
    case "circle":
      nd.attr("cx", cx)
        .attr("cy", cy)
        .attr("r", Math.sqrt(w*w + h*h)/2 + pad);
      break;
    case "rectangle":
      nd.attr("x", cx - w/2 - pad)
        .attr("y", cy - h/2 - pad)
        .attr("width", w + 2*pad)
        .attr("height", h + 2*pad);
      break;
  }

});

シェイプが追加され、テキストが追加されることに注意してください。thenシェイプは、テキストを上に表示するために配置されます。

2
Aleks Kissinger

私はこのガイドを似たようなことを成し遂げようとするのに非常に役立つと思いました:

https://www.dashingd3js.com/svg-text-element

上記のリンクに基づいて、このコードは円ラベルを生成します:

<!DOCTYPE html>
<html>
  <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
   </head>
<body style="overflow: hidden;">
<div id="canvas"  style="overflow: hidden;"></div>

<script type="text/javascript">

    var graph = {
        "nodes": [
            {name: "1", "group": 1, x: 100, y: 90, r: 10 , connected : "2"},
            {name: "2", "group": 1, x: 200, y: 50, r: 15, connected : "1"},
            {name: "3", "group": 2, x: 200, y: 130, r: 25, connected : "1"}
        ]
    }

    $( document ).ready(function() {

        var width = 2000;
        var height = 2000;

        var svg = d3.select("#canvas").append("svg")
                .attr("width", width)
                .attr("height", height)
                .append("g");

        var lines = svg.attr("class", "line")
                .selectAll("line").data(graph.nodes)
                .enter().append("line")
                .style("stroke", "gray") // <<<<< Add a color
                .attr("x1", function (d, i) {
                    return d.x
                })
                .attr("y1", function (d) {
                    return d.y
                })
                .attr("x2", function (d) {
                    return findAttribute(d.connected).x
                })
                .attr("y2", function (d) {
                    return findAttribute(d.connected).y
                })

        var circles = svg.selectAll("circle")
                .data(graph.nodes)
                .enter().append("circle")
                .style("stroke", "gray")
                .style("fill", "white")
                .attr("r", function (d, i) {
                    return d.r
                })
                .attr("cx", function (d, i) {
                    return d.x
                })
                .attr("cy", function (d, i) {
                    return d.y
                });

        var text = svg.selectAll("text")
                                .data(graph.nodes)
                                .enter()
                               .append("text");

        var textLabels = text
          .attr("x", function(d) { return d.x; })
          .attr("y", function(d) { return d.y; })
          .text( function (d) { return d.name })
          .attr("font-family", "sans-serif")
          .attr("font-size", "10px")
          .attr("fill", "red");

    });

    function findAttribute(name) {
        for (var i = 0, len = graph.nodes.length; i < len; i++) {
            if (graph.nodes[i].name === name)
                return graph.nodes[i]; // Return as soon as the object is found
        }
        return null; // The object was not found
    }


</script>
</body>
</html>
1
blue-sky