首页 > 解决方案 > 以不同的速率和位置绘制多折线图 d3

问题描述

我正在为 d3 v5 中的多折线图制作动画。它; 将佛罗里达州一个县的流动率与整个州的平均旅行距离进行比较。我已经成功生成了动画,并且过滤过程正常工作。我现在遇到的问题是,对于大多数县来说,这条线是在沿 x 轴的不同位置绘制的。佛罗里达线一直是动画的。两者的动画同时开始。令我困惑的是,对于某些选项,线条遵循预期的行为(在我的 x 轴的开头绘制)。发生这种情况有原因吗?

多折线图的不均匀动画

过滤数据:

function compare(county) {
// 3.1 - filter data based on select value
let countyData = data.filter(function(element) {
  return element.place === 'Florida' || element.place === county;
});

嵌套:

 countyData = d3
  .nest()
  .key(function(d) {
    return d.place;
  })
  .entries(countyData);

点击播放按钮后画线:

const countyLine = bounds
    .selectAll('lines')
    .data(countyData)
    .enter()
    .append('path')
    .attr('fill', 'none')
    .attr('class', 'chartLine')
    .attr('stroke', function(d) {
      if (d.key === 'Florida') {
        return '#00796b';
      }
      return '#fbc02d';
    })
    .attr('stroke-width', function(d) {
      if (d.key === 'Florida') {
        return '1';
      }
      return '2';
    })
    .attr('d', function(d) {
      return d3
        .line()
        .x(function(d) {
          return xScale(d.date);
        })
        .y(function(d) {
          return yScale(d.percent_change);
        })(d.values);
    });

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

  // Set Properties of Dash Array and Dash Offset and initiate Transition
  countyLine
    .attr('stroke-dasharray', `${totalLength} ${totalLength}`)
    .attr('stroke-dashoffset', totalLength)
    .transition()
    .delay(2000)
    .duration(7000)
    .ease(d3.easeLinear)
    .attr('stroke-dashoffset', 0);

首先我更新我的 y 轴并将线条动画延迟 2 秒。

对此的任何帮助将不胜感激!提前致谢 :)

标签: javascriptanimationd3.jsdata-visualizationlinechart

解决方案


推荐阅读