【发布时间】:2021-02-18 14:00:35
【问题描述】:
我正在创建一个带有网格线的 4 象限折线图。但是,网格似乎无法正常工作。当我平移轴时,它不会向两边移动。我也提供了一个小提琴here。
const f = (x) => {
return Math.sin(x)
}
const data = d3.ticks(-5, 5, 100).map((x) => {
const container = {
x: x,
y: f(x)
}
return container
})
const margins = { top: 20, right: 20, bottom: 30, left: 30 }
const width = 750 - margins.left - margins.right
const height = 750 - margins.top - margins.bottom
const svg = d3.select('#graph')
.append('svg')
.attr('width', width + margins.left + margins.right)
.attr('height', height + margins.top + margins.bottom)
.append('g')
.attr('transform', `translate(${margins.left}, ${margins.top})`)
const x = d3.scaleLinear([-5, 5], [0, width])
const y = d3.scaleLinear([-5, 5], [height, 0])
const xAxis = svg.append('g')
.attr('transform', `translate(0, ${y(0)})`)
.attr('class', 'x-axis')
const yAxis = svg.append('g')
.attr('transform', `translate(${x(0)}, 0)`)
.attr('class', 'y-axis')
xAxis.call(d3.axisBottom(x))
yAxis.call(d3.axisLeft(y))
d3.selectAll('g.x-axis g.tick')
.append('line')
.attr('class', 'gridline')
.attr('x1', 0)
.attr('y1', -height)
.attr('x2', 0)
.attr('y2', 0)
d3.selectAll('g.y-axis g.tick')
.append('line')
.attr('class', 'gridline')
.attr('x1', 0)
.attr('y1', 0)
.attr('x2', width)
.attr('y2', 0)
svg.append('path')
.datum(data)
.attr('fill', 'none')
.attr('stroke', 'steelblue')
.attr('stroke-width', 1.5)
.attr('d', d3.line(d => x(d.x), d => y(d.y)))
#graph {
text-align: center;
}
.gridline{
stroke: black;
shape-rendering: crispEdges;
stroke-opacity: 0.5;
}
<div id="graph"></div>
<script src="https://d3js.org/d3.v6.min.js"></script>
我使用this method 来创建网格线。
我希望网格扩展到我翻译的那一侧。谢谢。
【问题讨论】:
标签: javascript svg d3.js