问题
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);
回答1:
Append the grid-lines before appending the bars and they will come out in the background.
来源:https://stackoverflow.com/questions/48697167/how-to-move-grid-lines-behind-bar-graph-in-d3-js