gpt4 book ai didi

javascript - 如何为每个刻度绘制网格线?

转载 作者:太空宇宙 更新时间:2023-11-04 15:24:56 24 4
gpt4 key购买 nike

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

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

最佳答案

可以使用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,当然它也会匹配刻度数。

假设我通过 .ticks(20) 更改了刻度数 = 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;
}

希望这有帮助。

关于javascript - 如何为每个刻度绘制网格线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com