D3 js选择矩形

D3 js selecting rectangles in

我正在尝试使用 d3 js 库 v3 生成热图。 在尝试将数据映射到矩阵上时,数据映射是垂直完成的,但我需要水平映射数据。请参考所附图片以获得预期输出。

var data = [
    {score: 0.5, row: 0, col: 0},
    {score: 0.7, row: 0, col: 1},
    {score: 0.2, row: 0, col: 2},
    {score: 0.4, row: 1, col: 0},
    {score: 0.2, row: 1, col: 1},
    {score: 0.4, row: 1, col: 2},
    {score: 0.4, row: 2, col: 0},
    {score: 0.2, row: 2, col: 1},
    {score: 0.4, row: 2, col: 2}
];

//height of each row in the heatmap
//width of each column in the heatmap
var gridSize = 50,
    h = gridSize,
    w = gridSize,
    rectPadding = 60;

var colorLow = 'green', colorMed = 'yellow', colorHigh = 'red';

var margin = {top: 20, right: 80, bottom: 30, left: 50},
    width = 640 - margin.left - margin.right,
    height = 380 - margin.top - margin.bottom;

var colorScale = d3.scale.linear()
     .domain([-1, 0, 1])
     .range([colorLow, colorMed, colorHigh]);

var svg = d3.select("#heatmap").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 + ")");

var heatMap = svg.selectAll(".heatmap")
    .data(data, function(d) { return d.col + ':' + d.row; })
  .enter().append("svg:rect")
    .attr("x", function(d) { return d.row * w; })
    .attr("y", function(d) { return d.col * h; })
    .attr("width", function(d) { return w; })
    .attr("height", function(d) { return h; })
    .style("fill", function(d) { return colorScale(d.score); });

 var textLable =  svg.selectAll(".bartext")
        .data(data);
      textLable.exit().remove();
      textLable.enter()
              .append("text")
              .attr("class", "bartext")
              .attr("y", function(d) { return d.col * h * 1.2 ; })
               .attr("x", function(d) { return d.row * w * 1.2 ; })
         
              
    .attr("height", function(d) { return h; })
   
              .style("text-anchor", "middle")              
              
              .text(function(d,i){
                return i ;
              });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.4/d3.min.js"></script>
<div id='heatmap'></div>

http://jsfiddle.net/QWLkR/2/

Expected Output

在您的热图变量中,您将 X 坐标设置为等于行乘以宽度,这意味着更高的行将具有更高的 X 坐标,而它应该具有更高的 Y 坐标。交换这些以使代码按您想要的方式工作。

.attr("x", function(d) { return d.col * h; })
.attr("y", function(d) { return d.row * w; })