Подтвердить что ты не робот

D3 добавить текст в круг

Я пытаюсь добавить текст в круг. Я привел пример из http://mbostock.github.com/d3/tutorial/circle.html, но не смог получить правильный результат.

Фрагмент кода:

    var data;
    var code;
    d3.json("/json/trace.json", function(json) {
        data = json;
        console.log(data);
        // get code for visualization
        code = data["code"];
        alert(code); 
        var mainSVG = d3.select("#viz")
            .append("svg")
            .attr("width", 900)
            .attr("height", 900);
        mainSVG.append("circle")
        .style("stroke", "gray")
        .style("fill", "white")
        .attr("r", 100)
        .attr("cx", 300)
        .attr("cy", 300);
        circle = mainSVG.selectAll("circle").data([code]);

    }) ;

Любые предложения о том, как получить эту работу? Большое спасибо!

4b9b3361

Ответ 1

Вот пример, показывающий некоторый текст в кругах с данными из json файла: http://bl.ocks.org/4474971. Что дает следующее:

enter image description here

Основная идея заключается в том, чтобы инкапсулировать текст и круг в один и тот же "div", как в html, чтобы логотип и имя компании совпадали с тем же div в заголовке страницы,

Основной код:

var width = 960,
    height = 500;

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

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

а файл json:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

Полученный html-код показывает требуемую инкапсуляцию:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

Ответ 2

Увеличьте приведенный выше пример, чтобы он соответствовал фактическим требованиям, где кружок заполнен сплошным фоном, затем с полосатым рисунком и после этого текст node помещается в центр круга.

var width = 960,
  height = 500,
  json = {
    "nodes": [{
      "x": 100,
      "r": 20,
      "label": "Node 1",
      "color": "red"
    }, {
      "x": 200,
      "r": 25,
      "label": "Node 2",
      "color": "blue"
    }, {
      "x": 300,
      "r": 30,
      "label": "Node 3",
      "color": "green"
    }]
  };

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

svg.append("defs")
  .append("pattern")
  .attr({
    "id": "stripes",
    "width": "8",
    "height": "8",
    "fill": "red",
    "patternUnits": "userSpaceOnUse",
    "patternTransform": "rotate(60)"
  })
  .append("rect")
  .attr({
    "width": "4",
    "height": "8",
    "transform": "translate(0,0)",
    "fill": "grey"
  });

function plotChart(json) {
  /* Define the data for the circles */
  var elem = svg.selectAll("g myCircleText")
    .data(json.nodes)

  /*Create and place the "blocks" containing the circle and the text */
  var elemEnter = elem.enter()
    .append("g")
    .attr("class", "node-group")
    .attr("transform", function(d) {
      return "translate(" + d.x + ",80)"
    })

  /*Create the circle for each block */
  var circleInner = elemEnter.append("circle")
    .attr("r", function(d) {
      return d.r
    })
    .attr("stroke", function(d) {
      return d.color;
    })
    .attr("fill", function(d) {
      return d.color;
    });

  var circleOuter = elemEnter.append("circle")
    .attr("r", function(d) {
      return d.r
    })
    .attr("stroke", function(d) {
      return d.color;
    })
    .attr("fill", "url(#stripes)");

  /* Create the text for each block */
  elemEnter.append("text")
    .text(function(d) {
      return d.label
    })
    .attr({
      "text-anchor": "middle",
      "font-size": function(d) {
        return d.r / ((d.r * 10) / 100);
      },
      "dy": function(d) {
        return d.r / ((d.r * 25) / 100);
      }
    });
};

plotChart(json);
.node-group {
  fill: #ffffff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Ответ 3

Возможно, сделайте шаг назад и отбросьте json, пока не ухватитесь за теорию.

http://tributary.io/inlet/4132672/ (живой пример, представленный enjalot в этом видео. Я настоятельно рекомендую проверить другие видеоролики d3, которые у него есть.