Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move grid lines behind bar graph in d3.js?

So was trying to create a simple bar graph. Was playing around with the axis and wanted to draw gridlines behind the bar graph. The bar graph and gridlines are drawn, but gridlines are coming over the bars.

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);
like image 468
Aman Tewary Avatar asked Mar 06 '23 22:03

Aman Tewary


1 Answers

Append the grid-lines before appending the bars and they will come out in the background.

like image 163
brenzy Avatar answered Mar 20 '23 07:03

brenzy