Прямоугольники не появляются в правильном направлении - PullRequest
0 голосов
/ 11 января 2019

Я пытаюсь создать несколько прямоугольников в D3, получая данные из файла .csv.

Прямоугольники появляются, но не в правильном положении. Например, я хочу, чтобы первый запустился для x = 0 и y = 0, но вместо этого y неверен. А также я не могу правильно прочитать из файла письма. Это просто показывает мне «NaN» на левой оси, но я хочу, чтобы они появлялись внутри каждого прямоугольника.

Мой файл .csv это

x,y,width,height,color,txt
0,0,50,50,purple,A
80,40,100,400,blue,B
300,500,100,200,navy,C
320,306,100,100,green,D
800,500,50,50,red,E
850,550,150,100,gray,F
40,550,500,50,indigo,G
100,200,300,320,yellow,H

Я также пытался перевести все треугольники так же, как я делал для оси, но ничего не произошло, они исчезли.

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

.rect { fill-opacity:.50; stroke: rgb(60,100,200); stroke-width:1px;}

</style>
<body>

<!-- load the d3.js library -->     
<script src="//d3js.org/d3.v4.min.js"></script>
<script>

// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 1074 - margin.left - margin.right,
    height = 818 - margin.top - margin.bottom;

// set the ranges
var x = d3.scaleLinear()
      .range([0, width]);
var y = d3.scaleLinear()
      .range([height, 0]);

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
 .append("g")
  .attr("transform", 
      "translate(" + margin.left + "," + margin.top + ")");

// get the data
  d3.csv("rectangles.csv", function(error, data) {
    if (error) throw error;

// format the data
   data.forEach(function(d) {
   d.txt = +d.txt;
  });

 // Scale the range of the data in the domains
  x.domain([0, d3.max(data, function(d) { return d.x; })]);
  y.domain([0, d3.max(data, function(d) { return d.y; })]);

// append the rectangles for the bar chart
  svg.selectAll(".rect")
    .data(data)
  .enter().append("rect")
   .attr("class", "rect")
   .attr("x", function(d) { return x(d.x); })
   .attr("y", function(d) { return y(d.y); })
   .attr("width", function(d) { return d.width })
   .attr("height", function(d) { return d.height})
   .attr("fill", function(d) {return d.color});

  svg.selectAll("text")
    .data(data)
  .enter().append("text")
    .attr("fill","red")
    .attr("y", function(d) { return y(d.y); })
    .text(function(d) {return d.txt});

 // add the x Axis
 svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

 // add the y Axis
 svg.append("g")
  .call(d3.axisLeft(y));
});
 </script>
</body>

Я хочу создать все прямоугольники внутри двух осей с буквами внутри них.

1 Ответ

0 голосов
/ 11 января 2019

Для вашего rects правильная y-позиция:

.attr("y", function(d) { return y(d.y) - d.height; })

Поскольку вы хотите, чтобы основание из rect было размещено в вашей позиции y.

Ваш "txt" отображается как NAN, потому что вы приводите его к числу с такими строками:

data.forEach(function(d) {
  d.txt = +d.txt;
});

Просто удалите их.

Для позиционирования текста правильные расчеты:

.attr("y", function(d) { return y(d.y) - d.height/2; })
.attr("x", function(d) { return x(d.x) + d.width/2; })

Что перемещает его в центр rects.

Вот все это вместе.

редактирует

Так что это сложнее, чем я думал. Реальный расчет y:

.attr("y", function(d) { return  y(d.y) - (height - y(d.height)); })

И высота:

.attr("height", function(d) { return height - y(d.height); });

Обновление пример .

...