如何在每一个刻度线上绘制网格线?

时间:2018-08-26 13:10:29

标签: javascript d3.js

我有10个刻度的x轴。我想为每个刻度线绘制一条网格线。我的尝试在这里:

const dataSet = [
  0,
  10,
  20,
  30,
  40,
  50,
  60,
  70,
  80,
  90,
  100
];

const w = 1200;
const h = 250;
const padding = 20;
const paddingYaxis = 50;

const xScale = d3.scaleLinear()
               .domain([0,100])
               .range([paddingYaxis, w - 10]);

const svg = d3.select('#costSquareGraph');

svg.selectAll('line')
  .data(dataSet)
  .enter()   
  .append('line')
  .attr("x1", function(d) { return xScale(d); })
  .attr("y1", padding)
  .attr("x2", function(d) { return xScale(d); })
  .attr("y2", h - padding)
  .attr("stroke-width", 1)
  .attr("stroke", "#999");     

const xAxis = d3.axisBottom(xScale)
                .tickSizeOuter(-10)
                .tickPadding(5);

svg.append('g')
  .attr('transform', 'translate(0,' + (h - padding) + ')')
  .call(xAxis);

现场演示is here.

但是我的代码有问题。当标签数量增加时-我将不得不为新行编写代码。这是非常糟糕的做法。

我需要循环绘制所有可能的网格线。请帮助我。

PS:我使用D3 5.7.0

1 个答案:

答案 0 :(得分:1)

可以使用轴的tickSizeInner方法绘制网格线。您无需像在代码中那样专门绘制网格线。

示例:

d3.axisBottom(xScale).tickSizeInner(-height)

对于您而言,要包括填充,以上内容将更改为:

d3.axisBottom(xScale).tickSizeInner(-(h-padding))

代码段:

const dataSet = [
  0,
  10,
  20,
  30,
  40,
  50,
  60,
  70,
  80,
  90,
  100
];

const w = 1200;
const h = 250;
const padding = 20;
const paddingYaxis = 50;

const xScale = d3.scaleLinear()
               .domain([0,100])
               .range([paddingYaxis, w - 10]);

const svg = d3.select('#costSquareGraph');  

const xAxis = d3.axisBottom(xScale)
                .tickSizeInner(-(h-padding))
                .tickPadding(5);

svg.append('g')
  .attr('transform', 'translate(0,' + (h - padding) + ')')
  .call(xAxis);
  //.selectAll('.tick line').attr('y1', 3);
svg {
	width: 100%;

}

.tick line {
  stroke: #CCC;
}
.cost-square-wrap {
  width: 100%;
}
<script src="https://d3js.org/d3.v5.min.js"></script>


    <div class="cost-square-wrap">
			<svg id="costSquareGraph" viewbox="0 0 1200 250"></svg> 
		</div>

这只会更改刻度线的y2,当然也将与刻度线的数量匹配。

比方说,我将跳动次数= 20更改为.ticks(20)。片段:

const dataSet = [
  0,
  10,
  20,
  30,
  40,
  50,
  60,
  70,
  80,
  90,
  100
];

const w = 1200;
const h = 250;
const padding = 20;
const paddingYaxis = 50;

const xScale = d3.scaleLinear()
               .domain([0,100])
               .range([paddingYaxis, w - 10]);

const svg = d3.select('#costSquareGraph');  

const xAxis = d3.axisBottom(xScale)
                .tickSizeInner(-(h-padding))
                .tickPadding(5).ticks(20);

svg.append('g')
  .attr('transform', 'translate(0,' + (h - padding) + ')')
  .call(xAxis);
  //.selectAll('.tick line').attr('y1', 3);
svg {
	width: 100%;

}

.tick line {
  stroke: #CCC;
}
.cost-square-wrap {
  width: 100%;
}
<script src="https://d3js.org/d3.v5.min.js"></script>


    <div class="cost-square-wrap">
			<svg id="costSquareGraph" viewbox="0 0 1200 250"></svg> 
		</div>

还添加了一些CSS:

.tick line {
   stroke: #CCC;
}

希望这会有所帮助。

相关问题