gpt4 book ai didi

javascript - D3.js 更新堆积条形图

转载 作者:行者123 更新时间:2023-12-03 07:02:57 25 4
gpt4 key购买 nike

我基本上关注了this example构建堆积条形图。但是,我想通过下拉菜单更新数据。

我的逻辑是这样的:我的数据存储在包含 15 个对象的 JSON 数组中。我在 Javascript 中使用数组来存储每个对象,当我从下拉菜单中选择索引时,我想加载所选对象的 D3 可视化。

目前,我的堆积条形图可以正常工作,并且当我更改索引时,我可以正确更新/设置轴的动画,但我无法显示图表。由于某种原因,我必须按两次更新按钮才能显示图表,即使第一次单击时会显示轴。

我的代码是这样的:

d3.json 调用

...

函数更新(索引){

...

var layers = svg.selectAll(".layer")

layers.selectAll("rect")
.data(new_layers)
.exit()
.transition()
.duration(300)
.attr("y", function(d) { return -1 * y(d.y + d.y0); })
.remove();

layers
.transition()
.duration(300)
.remove()

var new_layer = svg.selectAll(".layer")
.data(new_layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) {
return color(i);
});

new_layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return y(d.y + d.y0); })
.attr("height", function(d) { return y(d.y0) - y(d.y + d.y0); })
.attr("width", x.rangeBand() - 1)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);

我有一种感觉,这是因为我创建了 new_layer 变量,也许在我第一次调用 update 时它没有完全初始化,所以我需要再次按它?不完全确定,因此我们将不胜感激任何指导。

我的代码结构基本上遵循第一句中链接的示例,但 d3 示例没有转换。

最佳答案

请遵循标准更新模式:https://bl.ocks.org/mbostock/3808218

就您的情况而言,如果您只想删除旧图层并重新绘制它们:

svg.selectAll(".layer").remove();

var new_layer = svg.selectAll(".layer")
.data(new_layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) {
return color(i);
});

new_layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return y(d.y + d.y0); })
.attr("height", function(d) { return y(d.y0) - y(d.y + d.y0); })
.attr("width", x.rangeBand() - 1)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);

此外,转换是异步执行的,因此即使您后面的代码按顺序在转换之后执行,当您到达后面的代码时,状态可能还没有被转换更新。

一般更新模式,供您引用:

function update(data) {

// DATA JOIN
// Join new data with old elements, if any.
var text = svg.selectAll("text")
.data(data);

// UPDATE
// Update old elements as needed.
text.attr("class", "update");

// ENTER
// Create new elements as needed.
text.enter().append("text")
.attr("class", "enter")
.attr("x", function(d, i) { return i * 32; })
.attr("dy", ".35em");

// ENTER + UPDATE
// Appending to the enter selection expands the update selection to include
// entering elements; so, operations on the update selection after appending to
// the enter selection will apply to both entering and updating nodes.
text.text(function(d) { return d; });

// EXIT
// Remove old elements as needed.
text.exit().remove();
}

关于javascript - D3.js 更新堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36950625/

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