Рисование нескольких кружков с текстом в них с помощью d3. js - PullRequest
1 голос
/ 20 апреля 2020

Я новый javascript программист. Я пытаюсь сделать визуализацию, которая состоит из кругов, основанных на категориях («в основном одна категория на каждом круге»). Моя проблема в том, что мой код печатает только один кружок со всеми категориями друг над другом.

 <script> 
        var width = 600;
        var height = 600;

        var data = d3.json("/data", function(error, data){
                    console.log(data)
        // Make SVG container 
        var svgContainer = d3.select("body")
                             .append("svg")
                             .attr("width", width)
                             .attr("height", height);

        var elem = svgContainer.selectAll("div")
                               .data(data);

        var elemEnter = elem.enter()
                            .append("g")

        var circles = elemEnter.append("circle")
                              .attr("cx", 100)
                              .attr("cy", 100)
                              .attr("r",80)
                              .style("fill", "blue")

        elemEnter.append("text")
                 .attr("dy", function(d){
            return d.SkillProficiencyId +80;
            }).attr("dx",function(d){ return d.SkillProficiencyId-1;})
                    .text(function(d){return d.CategoryName});
        });


    </script>

enter image description here

> Sample of my Data
(18) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
EmployeeId: 11111
AdUserName: null
FirstName: "ABC"
LastName: "DEF"
SkillId: 2346
CategoryName: "Adaptive Security Architecture"
SkillProficiencyId: 1
SkillProficiencyLevel: "Beginner"
__proto__: Object
1: {EmployeeId: 11111, AdUserName: null, FirstNam...
2: {EmployeeId: 11111, AdUserName: null, FirstName....

1 Ответ

3 голосов
/ 20 апреля 2020

Я создал пример с динамически созданными кругами, с текстом внутри по центру.

https://codepen.io/mayconmesquita/pen/OJyRZxX

Демонстрация:

enter image description here

Код JS: [Отредактировано *]

var width = 600;
var height = 600;

// Place your JSON here.
var data = [
  { CategoryName: 'Adaptive Security', SkillProficiencyId: 1 },
  { CategoryName: 'Programmer', SkillProficiencyId: 2 },
  { CategoryName: 'Coffee Drinker', SkillProficiencyId: 3 }
];

/*
  This 'cxBase' will be multiplied by element's index, and sum with offset.
  So for 3 elements, cx = 0, 200, 400 ...
  All these values changeable by this vars.
*/
const cxBase = 200;
const cxOffset = 100;

console.log(data);

// Make SVG container  
var svgContainer = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);

// This function will iterate your data
data.map(function(props, index) {
  var cx = cxBase * (index) + cxOffset; // Here CX is calculated

  var elem = svgContainer.selectAll("div").data(data);

  var elemEnter = elem.enter()
  .append("g")

  var circles = elemEnter.append("circle")
  .attr("cx", cx)
  .attr("cy", 100)
  .attr("r", 80)
  .style("fill", "blue");

  elemEnter
  .append("text")
  .style("fill", "white")
  .attr("dy", function(d){
    return 105;
  })
  .attr("dx",function(d){
    return cx - (props.CategoryName.length * 3.5);
  })
  .text(function (d) {
    return props.CategoryName
  });
});

Редактировать:

  1. По просьбе автора я улучшил код. Теперь координата cx круга вычисляется динамически на основе индекса элемента массива.
/*
  This 'cxBase' will be multiplied by element's index, and sum with offset
  So for 3 elements, cx = 0, 200, 400 ...
  All these values changeable by this vars.
*/
const cxBase = 200;
const cxOffset = 100;
...