Javascript d3 将文本添加到圆圈

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13615381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:29:50  来源:igfitidea点击:

d3 add text to circle

javascriptsvgd3.js

提问by gizmo

I am trying to add some text into circle. I have been following example from a mbostock tutorial, but wasn't able to get the right output.

我正在尝试将一些文本添加到圆圈中。我一直在关注mbostock 教程中的示例,但无法获得正确的输出。

The code snippet is:

代码片段是:

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

Any suggestions how to get this work?

任何建议如何获得这项工作?

回答by Christopher Chiche

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

这是一个示例,其中显示了一些圆圈中的文本,其中包含来自 json 文件的数据:http: //bl.ocks.org/4474971。这给出了以下内容:

enter image description here

在此处输入图片说明

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same divin a page header.

这背后的主要思想是将文本和圆圈封装在与div您在 html 中所做的相同的“ ”中,以便div在页眉中具有相同的徽标和公司名称。

The main code is:

主要代码是:

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

and the json file is:

和 json 文件是:

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

The resulting html code shows the encapsulation you want:

生成的 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>

回答by Manish Kumar

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

扩展上面的例子以适应实际需求,其中圆形填充为纯背景色,然后用条纹图案填充,然后将文本节点放置在圆圈的中心。

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>

Output:

输出:

enter image description here

在此处输入图片说明

Below is the link to codepenalso:

下面是链接codepen

看笔 D3-Circle-Pattern-TextD3-Circle-Pattern-Textby Manish Kumar (@mkdudeja@mkdudeja) 上CodePen代码笔

Thanks, Manish Kumar

谢谢,曼尼什库马尔

回答by Kenaa

Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.

这是我认为更简单的一种方法:一般的想法是,您希望将文本元素附加到圆元素,然后使用其“dx”和“dy”属性,直到将文本定位在圆中的点喜欢。在我的示例中,我对 dx 使用了负数,因为我希望文本从中心左侧开始。

const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]

const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)

const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)