如何在d3.js中移动条形图后面的网格线?

时间:2018-02-09 00:54:04

标签: javascript d3.js

所以试图创建一个简单的条形图。正在玩轴,想在条形图后面绘制网格线。绘制条形图和网格线,但网格线正在越过条形线。

JS

var dataArray = [6,7,7.2,7.7,7.7,9.5,11.7,10.5,10.1];

var margin = {top: 80, right: 40, bottom: 0, left: 5};

var y = d3.scaleLinear()
          .domain([0,12])
          .range([300,0]);

var ticks = [0,2,4,6,8,10,12];
var gridlines = d3.axisLeft(y)
                  .tickValues(ticks)
                  .tickSize(-innerWidth);

var yAxis = d3.axisLeft(y)
              .tickValues(ticks)
              .tickSize(0);


var svg = d3.select("#barGraph1")
            .append("svg")
              .attr("height","100%")
              .attr("width","100%");

var barGroup = svg.append("g")
                        .attr("transform","translate("+margin.top+","+margin.left+")");
barGroup.selectAll("rect")
             .data(dataArray)
             .enter().append("rect")
                      .attr("height",function(d){return 300-y(d);})
                      .attr("width","35")
                      .attr("fill","red")
                      .attr("transform", "translate(30,0)")
                      .attr("x",function(d,i){ return 70*i;})
                      .attr("y",function(d){ return y(d);});

//gridlines
barGroup.append("g")
          .attr("class", "grid")
          .call(gridlines);

barGroup.append("g")
          .attr("class","axisY")
          .call(yAxis);

1 个答案:

答案 0 :(得分:2)

在附加条形之前附加网格线,它们将在后台出现。