gpt4 book ai didi

javascript - D3.js 图表响应行为

转载 作者:行者123 更新时间:2023-12-02 13:56:43 25 4
gpt4 key购买 nike

当窗口宽度发生变化时,我尝试设置监听器以使用 jQuery 更改图表宽度:

// Get width of parent div with jQuery

var widthContainer = $( ".chart" ).parent().width();

//set margins
// margin conventions https://bl.ocks.org/mbostock/3019563

var margin = {top: 0, right: 0, bottom: 30, left: 40};
var width = widthContainer - margin.left - margin.right;
var height = 211 - margin.top - margin.bottom;

// set chart dimensions

var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");


// listener

function changeWidth(){
widthContainer = $( ".chart" ).parent().width();
width = widthContainer - margin.left - margin.right;
}

$(window).resize(function(){
changeWidth();
console.log(widthContainer);
});

changeWidth() 函数更改 widthContainer 变量,但图表尺寸不会更改。为什么?

这是一个工作代码笔(第 13 到 40 行): http://codepen.io/aitormendez/pen/LbRyWa?editors=0011

提前谢谢

最佳答案

您当前的changeWidth()仅计算新的宽度。您需要将新宽度设置为您想要的元素。您还需要更新图表 x 比例并重新绘制图表。

快速更新您的codepen(我将changeWidth和resize移动到底部并添加重绘功能)。

var redraw = function(newWidth) {
// update xscale
escalax.range([0, newWidth]);
d3.select('.xaxis').call(xAxis);
deuda.selectAll("rect")
.attr("width", function(d) {
return rr(escalax(d[1]));
});
recono.selectAll("rect")
.attr("x", function(d) {
return rr(escalax(d[1]));
})
.attr("width", function(d) {
return rr(escalax(d[2]));
});
provee.selectAll("rect")
.attr("x", function(d) {
return rr(escalax(d[1] + d[2]));
})
.attr("width", function(d) {
return rr(escalax(d[3]));
});
credito.selectAll("rect")
.attr("x", function(d) {
return rr(escalax(d[1] + d[2] + d[3]));
})
.attr("width", function(d) {
return rr(escalax(d[3]));
});
}

function changeWidth() {
widthContainer = $(".chart").parent().width();
width = widthContainer - margin.left - margin.right;

// update chart width
d3.select('.chart')
.attr('width', width);

// redraw chart
redraw(width);
}

$(window).resize(function() {
changeWidth();
console.log(widthContainer);
});

http://codepen.io/anon/pen/JbboQL?editors=1010

关于javascript - D3.js 图表响应行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40648113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com