Javascript 如何找到d3中的最后一个数据点并在其上画一个圆和一条线?
我在d3中有一个基本的折线图,可以正确显示。我需要找到数据的最后一个入口点,在上面画一个圆圈和一条虚线,如上图所示 这是我目前的d3代码:Javascript 如何找到d3中的最后一个数据点并在其上画一个圆和一条线?,javascript,typescript,svg,d3.js,Javascript,Typescript,Svg,D3.js,我在d3中有一个基本的折线图,可以正确显示。我需要找到数据的最后一个入口点,在上面画一个圆圈和一条虚线,如上图所示 这是我目前的d3代码: const xScale = scaleTime() .range([0, width]) .domain( extent(data, (d: { week: any }) => { return d.week; }) ); const yScale =
const xScale = scaleTime()
.range([0, width])
.domain(
extent(data, (d: { week: any }) => {
return d.week;
})
);
const yScale = scaleLinear()
.range([height, 0])
.domain([
min(data, (d: { index: number }) => {
return d.index;
}) - 20,
max(data, (d: { index: number }) => {
return d.index;
}) + 20
]);
const xAxis = axisBottom(xScale)
.ticks(data.length);
const svg = select(svgRef.current);
svg
.select(".x-axis")
.style("transform", `translateY(${height}px)`)
.call(xAxis);
const yAxis = axisLeft(yScale);
svg
.select(".y-axis")
.call(yAxis);
const myLine = line()
.x((d: { week: any }) => xScale(d.week))
.y((d: { index: any }) => yScale(d.index))
.curve(curveCardinal);
svg
.selectAll(".line")
.data([data])
.join("path")
.attr("class", "data-circle")
.attr("d", myLine)
.attr("fill", "none")
.attr("stroke", "purple")
.attr("stroke-width", "5px");
// draw circle here -- TODO
svg
.selectAll(".data-circle")
.data([data])
.append("circle")
.attr("r", 7.5);
我试着在它周围选择合适的元素,它可以返回数组中的最后一个条目,但是我不断地出错,我不确定这是否只是一个简单的更改
默认情况下,圆圈不必在鼠标悬停时绘制。如果加载了不同的数据,则会自动调整。计算每次更新时的点坐标,如果已创建点,则选择该点或创建一个新点:
const lastData = data[data.length-1];
const y = yScale(lastData.index));
const x = xScale(lastData.week));
let lastPoint = svg.select('.last-point');
let lastLine = svg.select('.last-line');
if (!lastPoint.node()) {
lastPoint = svg.append('circle')
.classed('last-point', true)
.style('fill', 'purple')
.attr('r', 7.5);
lastLine = svg.append('line')
.classed('last-line', true)
.attr('stroke-dasharray', '5,5')
.style('stroke', 'gray');
}
lastPoint
.attr('cx', x)
.attr('cy', y);
lastLine
.attr('x1', x)
.attr('x2', x)
.attr('y1', y)
.attr('y2', height);