D3.JS - 折线图 - 响应式 - 无法找到更新折线的 x 值的方法

D3.JS - Line chart - responsive - can't find a way to update Line's x-values

我正在尝试制作一个水平响应的 D3.JS 折线图 - 我的作品可以在这个 CodePen

中看到

我的问题是在图表宽度发生变化时更新线条数据点的 x 值位置。 x 轴正在调整大小。

在我的 Javascript 中,我有一个名为 resizeChart 的函数,当浏览器 window 的宽度发生变化时调用该函数:

  function resizeChart() {

currentWidth = parseInt(d3.select('#div_basicResize').style('width'), 10)
Svg.attr("width", currentWidth - 60)

x.range([20, currentWidth - 100]);
xAxis.call(d3.axisBottom(x));

var self = this;

Svg.selectAll("path")
  .data(data)
  .attr("x", function (d) {
    return self.x(d.period);
  });

}

问题出在 Svg.selectAll - 因为它似乎没有更新线的 x 值。

好吧,SVG 路径元素没有 x 属性(只有 d 属性,这就是您使用上面的一些行来附加路径的属性)。

就是说,只需为您的选择命名...

var path = Svg.append("path")
    //etc...

...并且,在 resizeChart 内,再次设置 d 属性,在更改 x 比例范围后:

path.attr("d", line);

下面是修改后的代码:

var Svg = d3.select("#div_basicResize")
  .append("svg")
  .attr("height", 0)

var data = [{
    "period": 2010,
    "count": 166
  },
  {
    "period": 2011,
    "count": 192
  },
  {
    "period": 2012,
    "count": 158
  },
  {
    "period": 2013,
    "count": 183
  },
  {
    "period": 2014,
    "count": 174
  },
  {
    "period": 2015,
    "count": 197
  },
  {
    "period": 2016,
    "count": 201
  },
  {
    "period": 2017,
    "count": 195
  },
  {
    "period": 2018,
    "count": 203
  },
  {
    "period": 2019,
    "count": 209
  },
  {
    "period": 2020,
    "count": 208
  }
]

var Svg = d3.select("#div_basicResize")
  .append("svg")
  .attr("height", 400);

var x = d3.scalePoint()
  .domain(
    data.map(function(d) {
      return d.period;
    })
  )
  .range([20, 20]);

var xAxis = Svg.append("g").attr(
  "transform",
  "translate(" + 20 + "," + 360 + ")"
);

var max =
  d3.max(data, function(d) {
    return +d.count;
  }) + 10;

var min =
  d3.min(data, function(d) {
    return +d.count;
  }) - 10;

var y = d3.scaleLinear()
  .domain([min, max])
  .range([360, 0]);

Svg.append("g")
  .attr("transform", "translate(" + 40 + ",0)")
  .call(d3.axisLeft(y));

var self = this;

var line = d3.line()
  .x(function(d) {
    return x(d.period) + 20;
  })
  .y(function(d) {
    return y(+d.count);
  });

var path = Svg.append("path")
  .datum(data)
  .attr("fill", "none")
  .attr("stroke", "black")
  .attr("stroke-width", 1)
  .attr("d", line);

function resizeChart() {

  currentWidth = parseInt(d3.select('#div_basicResize').style('width'), 10)
  Svg.attr("width", currentWidth - 60)

  x.range([20, currentWidth - 100]);
  xAxis.call(d3.axisBottom(x));

  //This is where I'm trying to update x value
  path.attr("d", line);
}

resizeChart()
window.addEventListener('resize', resizeChart);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<div id="div_basicResize"></div>