Текст внутри круга SVG в D3 не отображается

1

Я пытаюсь добавить текст в кругах SVG как этот пример, на моей карте D3. Я видел много похожих вопросов, размещенных на 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");

        });
Теги:
d3.js
svg
text

1 ответ

2
Лучший ответ

Причина, по которой text не подходит, объясняется тем, что вы не указали ни одного места, в котором оно должно появиться.

Для кругов вы даете cx и cy но ничего для текста.

Лучшим подходом было бы создание такой группы:

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})
  • 0
    Спасибо! (Работает, но не с функцией масштабирования)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню