我有一个 D3 条形图,最初绘制了一些数据。我将每 2 秒获取新数据。此新数据可以是新项目或现有项目的新计数。我想相应地更新图表。
这是我试过的:
https://jsfiddle.net/rutwick/an1d95h1/2/
var sales = [
{ product: 'Hoodie', count: 7 },
{ product: 'Jacket', count: 6 },
{ product: 'Snuggie', count: 9 },
{ product: 'Beanie', count: 8 }
];
var startTimer = false;
function drawGraph() {
//select the svg
var svg = d3.select('svg');
//Select all the rect elements and assign the data to them
var rects = svg.selectAll('rect')
.data(sales);
//This will access the rect element for creating new rect elements
var newRects = rects.enter();
// recall that scales are functions that map from
// data space to screen space
// Max limit for Y axis
var maxCount = d3.max(sales, function(d, i) {
return d.count;
});
//X axis will have bars, hence ordinal scale used
//domain - data - Product values
//Rangebound specifies max limit and the padding around the bands
var x = d3.scale.ordinal()
.domain(sales.map(function(d) {
return d.product;
}))
.rangeRoundBands([0, 500], 0.10); //300 = Total width of all bars, 0.10 = Factor of space between the bars
//Y axis is linear, hence linear scale used
var y = d3.scale.linear()
.range([400, 0])
.domain([0, maxCount]);
newRects.append('rect')
.attr('x', function(d) {
return x(d.product);
})
.attr('y', function(d, i) {
return y(d.count);
})
.attr('width', x.rangeBand())
.attr('height', function(d, i) {
return 400 - y(d.count);
});
startTimer = true;
rects.exit().remove();
}
function updateGraph(){
if(!startTimer) {
return;
}
var rand = Math.floor(Math.random() * sales.length);
/*if(sales[rand].count % 2 === 0) {
sales[rand].count += 2;
console.log(sales[rand].count);
}*/
sales.push({ product: 'Denim', count: 1 });
sales.push({ product: 'Sweatshirt', count: 12 });
drawGraph();
}
setInterval(updateGraph, 2000);
drawGraph();
它会更新,但不会重绘图表。只需在旧条上添加新条。我目前的计划包括使用 jQuery 删除所有 rect 元素,但我不知道它是否可行。
在 x 轴和 y 轴上更新完整图表究竟需要做什么?
最佳答案
你可以这样做:
首先你需要像这样定义对象:
var rects = svg.selectAll('rect')
.data(sales, function(d){/*Unique ID of a record*/ return d.product;});
现在像这样创建矩形:
newRects.append('rect');
现在用新的宽度和高度更新所有的矩形。
//do update
d3.selectAll("rect")
.attr('class', "rects")
.attr('x', function(d) {
console.log(d)
return x(d.product);
})
.attr('y', function(d, i) {
return y(d.count);
})
.attr('width', x.rangeBand())
.attr('height', function(d, i) {
return 400 - y(d.count);
});
最后删除已删除数据的柱:
//remove not there
rects.exit().remove()
你的代码没有更新的问题:
执行此操作时,属性仅在创建时更新
newRects.append('rect')
.attr('x', function(d) {
return x(d.product);
})
.attr('y', function(d, i) {
return y(d.count);
})
.attr('width', x.rangeBand())
.attr('height', function(d, i) {
return 400 - y(d.count);
});
工作代码 here
希望这对您有所帮助!
关于javascript - D3 - 每 2 秒更新条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34850771/