【问题标题】:d3 add text to circled3将文本添加到圆圈
【发布时间】:2012-11-16 21:54:11
【问题描述】:

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

代码sn-p是:

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

对如何完成这项工作有任何建议吗?

【问题讨论】:

  • 也许,退后一步,放下 json,直到你掌握了理论。 tributary.io/inlet/4132672(现场示例,由 enjalot 在此 video 中介绍。我强烈建议查看他拥有的其他 d3 视频。
  • 我尝试了提供的链接中的简单示例,但无法正常工作。无论如何,谢谢
  • 你没有看到里面有文字的 3 个圆圈?
  • 不-这就是我问的原因:)
  • 你有机会使用 firefox 吗?

标签: javascript svg d3.js


【解决方案1】:

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

这背后的主要思想是将文本和圆圈封装在同一个“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>

jsfiddle 与工作代码:http://jsfiddle.net/chrisJamesC/DY7r4/

【讨论】:

  • 天哪,它什么也没显示——即使我修复了';'来自 .attr("cy", 300);只要我的代码不添加一些文本,它就可以工作
【解决方案2】:

这是一种我认为更简单的方法: 一般的想法是,您希望将文本元素附加到圆形元素,然后使用其“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)

【讨论】:

    【解决方案3】:

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

    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;
    }
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"&gt;&lt;/script&gt;

    输出:

    下面是codepen的链接:

    请参阅 CodePen 上 Manish Kumar (@mkdudeja) 的 Pen D3-Circle-Pattern-Text

    谢谢, 马尼什·库马尔

    【讨论】:

    • 您好,需要一点帮助。就我而言,圆圈之间的文字隐藏在后面。如果我增加圆圈的不透明度,我可以看到文本,但如果圆圈颜色是纯色的,它会被隐藏。我是否遗漏了将文本置于圆圈上方的内容。谢谢
    • 唯一的问题是确保你只在创建圆圈后在圆圈上写文字。如果您在创建圆圈之前编写文本,则文本将不可见。基本上在 D3 中,一切都是一层。稍后创建的图层将覆盖之前的图层。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    相关资源
    最近更新 更多