【问题标题】:Using General update pattern in line graph在折线图中使用一般更新模式
【发布时间】:2019-06-04 05:29:47
【问题描述】:

我有一个演示 here

它是一个在 Angular 应用中使用 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() 

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    你在圆的选择和线的选择上都有问题。

    圈子的选择:

    1. 您正在选择"line-circle"。取而代之的是,您必须按类选择:".line-circle";
    2. 您正在重新分配 circle 选择:

      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);
    

    这是您的分叉代码:https://stackblitz.com/edit/basic-scatter-mt-vvdxqr?file=src/app/bar-chart.ts

    【讨论】:

      猜你喜欢
      • 2016-03-21
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多