D3.JS - 折线图 - 响应式 - 找不到更新折线的 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值。

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

也就是说,只要说出你的选择。。。

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

并且,在resizeChart内,在改变x标度范围后,再次设置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>

最新更新