简体   繁体   English

创建位置/并使用D3在JavaScript /或Coffee中使用“ g”和svg在圆中添加文本

[英]create position / and add text in circle using D3 using “g” and svg in JavaScript /or Coffee

so I am trying to seperate each cicle to look something like this 所以我试图分离每个小柱看起来像这样

![enter image description here][1]

here 这里 在此处输入图片说明

but with the text inside , but I couldnt' figure it out how my circle would not spread out as I use this coffescript code below 但是里面有文字,但是我无法弄清楚当我使用下面的这段代码时,圆圈不会散开

svg_w = 800
svg_h = 400
svg = d3.select("body").append("svg").attr("width", svg_w).attr("weight", svg_h)

list = [1,2,3,4,5]
dataset = (x*10 for x in list)
console.log dataset


nodes = svg.append("g").attr("class", "nodes").selectAll("circle")
        .data(dataset).enter().append("g")
            .attr("transform", (d, i) ->

                  d.x = i * 70 + 50
                  d.y = svg_h / 2

                  "translate(" + d.x + "," + d.y + ")"

                )

nodes.append("circle").attr("class", "node").attr "r", 20
nodes.append("text").attr("text-anchor", "middle").text (d) ->d.name

My result show all my circle to upper left coner 我的结果显示我所有的圆圈都在左上角

在此处输入图片说明

Any suggestion ? 有什么建议吗?

Thanks 谢谢

The problem is that you're trying to set properties ( dx and dy ) on a number instead an object. 问题是您试图在数字而不是对象上设置属性( dxdy )。 This doesn't work and your translation is undefined. 这不起作用,您的翻译未定义。 Use separate variables instead, eg 改用单独的变量,例如

 dx = i * 70 + 50
 dy = svg_h / 2
 "translate(" + dx + "," + dy + ")"

The text doesn't show up because you're referencing a property .name that doesn't exist. 该文本未显示,因为您引用的属性.name不存在。 Also, black text on a black circle isn't visible. 此外,黑色圆圈上的黑色文字也不可见。 You can fix this easily by giving the text a different color and appending the number as the text: 您可以通过为文本提供不同的颜色并将数字附加为文本来轻松解决此问题:

nodes.append("text").attr("text-anchor", "middle").text (d) ->d

Complete example here . 这里完整的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM