javascript - D3 中的 SVG 圆圈内的文本不显示

标签 javascript d3.js svg text

我正在尝试在 SVG 圆圈内附加文本,例如 this我的 D3 map 中的示例。我在 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");

        });

最佳答案

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

关于javascript - D3 中的 SVG 圆圈内的文本不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411365/

相关文章:

D3.js 4 直方图,带有来自 AJAX 的 JSON

javascript - Element.getElementById() 不工作

html - 如何在其父 div 中调整大小、居中对齐和响应 SVG 文件?

javascript - 简单的谷歌地图在 JsFiddle 中不起作用

javascript - 如何使用 javascript 按钮切换 url

javascript - 是否可以进行六边形拖放?

javascript - D3 示例中使用的 flare json 中的 "size"是什么?

javascript - d3 v4 折线图过渡不起作用

javascript - 如何将此 SVG 三 Angular 形转换为 "wandering"路径表示?

javascript - Extjs 存储不适合 JSON