D3中的SVG Circle内的文字没有显示

时间:2017-07-31 08:53:17

标签: javascript d3.js svg text

我正尝试将SVG圈内的文字附加到我的D3地图中的 this示例中。我在SO上发布了很多类似的问题 - 我已经用它们来编写下面的代码,但是不明白为什么它根本没有显示出来。

d3.json("https://raw.githubusercontent.com/d3/d3.github.com/master/world-110m.v1.json", function (error, topo) {
            if (error) throw error;

            gBackground.append("g")
                .attr("id", "country")
                .selectAll("path")
                .data(topojson.feature(topo, topo.objects.countries).features)
                .enter().append("path")
                .attr("d", path);


            gBackground.append("path")
                .datum(topojson.mesh(topo, topo.objects.countries, function (a, b) { return a !== b; }))
                .attr("id", "country-borders")
                .attr("d", path);


            console.log("Background Drawn");

           var point = gPoints.selectAll("circle")
                .data(pointsData)     
                .enter()            
                .append("circle")    
                .attr("cx", function (d) { return d.location[0]; })
                .attr("cy", function (d) { return d.location[1]; })
                .attr("r", 10)
                //Other attributes and mouseovers, etc


           var texts = gPoints.selectAll("text")
               .data(pointsData)
               .enter()
               .append("text")
               .text(function (d) { return d.performance; });

            console.log("Points Drawn");

        });

1 个答案:

答案 0 :(得分:2)

text未出现的原因是:您没有指定需要出现的任何位置。

对于圈子,您提供了cxcy,但没有提供任何内容。

更好的方法是建立一个这样的群体:

var elem = gPoints.selectAll("g .myCircleText").data(pointsData)
/*Create and place the "blocks" containing the circle and the text */  
var elemEnter = elem.enter()
    .append("g")
    .classed("myCircleText", true) //add a class to the group
    .attr("transform", function(d){return "translate("+d.location[0]+","+ d.location[1]+")"})

如上所示给小组翻译(这样你就不需要给cx和cy组翻译到所需的点)。

现在在群组中圈出这样的圈子:

/*Create the circle for each block */
var circle = elemEnter.append("circle")
    .attr("r", 10 )
    .attr("stroke","black")
    .attr("fill", "white")

现在在组内创建文本

/* Create the text for each block */
elemEnter.append("text")
    .attr("dx", function(d){return -20})//so that it comes 20 pixel from center.
    .text(function(d){return d.performance})