Javascript 在折线图中使用通用更新模式

Javascript 在折线图中使用通用更新模式,javascript,d3.js,Javascript,D3.js,我有一个演示 这是一个在角度应用程序中使用D3的线条形图 我希望图表能够做出响应,这样当调整页面大小时,图表的宽度将增加,高度将保持不变 我通过捕获窗口大小,然后调用绘制图表的函数来实现这一点 这适用于轴,但我无法获得要重新绘制的线和点 我想这与我试图告诉我们更新模式的方式有关 如何使用更新模式重新绘制此折线图 const that = this; const valueline = d3.line() .x(function (d, i) { return that.x(d.dat

我有一个演示

这是一个在角度应用程序中使用D3的线条形图

我希望图表能够做出响应,这样当调整页面大小时,图表的宽度将增加,高度将保持不变

我通过捕获窗口大小,然后调用绘制图表的函数来实现这一点

这适用于轴,但我无法获得要重新绘制的线和点

我想这与我试图告诉我们更新模式的方式有关

如何使用更新模式重新绘制此折线图

const that = this;
const valueline = d3.line()
  .x(function (d, i) {
    return that.x(d.date) + 0.5 * that.x.bandwidth();
  })
  .y(function (d) {
    return that.y(d.value);
  });

this.x.domain(data.map((d: any) => d.date));

this.y.domain(d3.extent(data, function (d) {
  return d.value
}));

const thisLine = this.chart.append("path")
  .data([data])
  .attr("class", "line")
  .attr("d", valueline);

const totalLength = thisLine.node().getTotalLength();

thisLine.attr("stroke-dasharray", totalLength + " " + totalLength)
  .attr("stroke-dashoffset", totalLength);

thisLine.transition()
  .duration(1500)
  .attr("stroke-dashoffset", 0)

let circle = this.chart.selectAll("line-circle")
  .data(data);

circle = circle  
  .enter()
    .append("circle")
    .attr("class", "line-circle")
    .attr("r", 4)
    .attr("cx", function (d) {
      return that.x(d.date) + 0.5 * that.x.bandwidth();
    })
    .attr("cy", function (d) {
      return that.y(d.value);
    })  

circle  
  .attr("r", 4)
  .attr("cx", function (d) {
    return that.x(d.date) + 0.5 * that.x.bandwidth();
  })
  .attr("cy", function (d) {
    return that.y(d.value);
  })   

circle
  .exit()
  .remove() 

圆的选择和线的选择都有问题

圆圈的选择:

circle = circle.enter()//etc...
  • 您正在选择
    “直线圆”
    。相反,您必须按类选择:
    “.linecircle”
  • 您正在重新指定
    圆圈
    选择:

    circle = circle.enter()//etc...
    
    不要这样做,否则
    circle
    将指向输入选择,而不再指向更新选择。只要做:

    circle.enter()//etc...
    
  • 路径:

    每次调用函数时都会附加一个新路径。不要那样做。相反,选择现有路径并更改其
    d
    属性,如果没有路径,则追加新路径。这两种行为都可以通过此代码实现:

    let thisLine = this.chart.selectAll(".line")
        .data([data]);
    
    thisLine = thisLine.enter()
        .append("path")
        .attr("class", "line")
        .merge(thisLine)
        .attr("d", valueline);
    
    这是您的分叉代码: