如何在d3.js中将网格线移动到条形图后面? [英] How to move grid lines behind bar graph in d3.js?

查看:251
本文介绍了如何在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);

推荐答案

在附加条形之前附加网格线,它们将在背景中出现.

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

这篇关于如何在d3.js中将网格线移动到条形图后面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆