首页 > 解决方案 > D3.JS - 折线图 - 响应式 - 找不到更新 Line 的 x 值的方法

问题描述

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

我的问题是当图表的宽度发生变化时更新 Lines 数据点的 x 值的位置。x 轴的大小调整得很好。

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

  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 - 因为它似乎没有更新 Line 的 x 值。

标签: javascriptsvgd3.jsresponsive

解决方案


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

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

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

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

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>


推荐阅读