I want to update a bar chart, but it "remembers" the length of the data i initialized it with. Here is what I think I do:
I would like the update to cause the bar chart to display only the remaining objects in the array without the gap. What am I doing wrong?
You can find the code here: http://tributary.io/inlet/8919193 to play with it. Or in plain form here:
var svg = d3.select("svg");
var BarChart = function BarChart( chart_attributes ){
// hide variables within function scope
var chart = {},
data;
// data setter and getter
chart.data = function( new_data ){
if( new_data ){ data = new_data; }
return data;
};
// update data and redraw chart
chart.update = function( new_data ){
// update data
if( !new_data ){ console.log("chart.update() - no data set!"); }
else{ chart.data( new_data ); }
// redraw
var bar_attr = chart_attributes.bars;
var groups = svg.selectAll("g").data( chart.data(), function(d){ return d.NAME } );
var g = groups.enter().append("g")
.attr("transform", function(d, i) { return "translate(100," + ((i * bar_attr.height)+100) + ")"; });
var bars = g.append("rect")
.attr("x", bar_attr.x)
.attr("height", bar_attr.height-1).transition()
.attr("width", function(d,i){return d.INTENSITY*10} );
g.append("text")
.attr("y", bar_attr.height-2 )
.attr("x", 0)
.attr("font-size", bar_attr.height )
.text( bar_attr.label);
groups.exit().remove();
};
return chart;
};
var data = [
{ "INTENSITY": 9, "NAME": "label 1"},
{ "INTENSITY": 10, "NAME": "label 2"},
{ "INTENSITY": 10, "NAME": "label 3"},
{ "INTENSITY": 13, "NAME": "label 4"},
{ "INTENSITY": 21, "NAME": "label 5"}
];
var margin_top = 50,
margin_left = 70,
bar_height = 20;
var bar_attributes = {
"x": margin_left,
"y": function(d,i){ return (i*bar_height)+margin_top;},
"height": bar_height,
"width": function(d,i){ return d.INTENSITY*10},
"label": function(d,i){ return d.NAME }
};
var attr = {"bars": bar_attributes };
var chart = new BarChart( attr );
chart.update(data);
data.splice(1,1)
chart.update(data);
The problem is that you're not updating the positions of the bars for updated data. The code that sets the position of the g elements is only run on new data:
var g = groups.enter().append("g")
.attr("transform", function(d, i) { return "translate(100," + ((i * bar_attr.height)+100) + ")"; });
Replacing this with
var g = groups.enter().append("g");
groups.attr("transform", function(d, i) { return "translate(100," + ((i * bar_attr.height)+100) + ")"; });
fixes the problem -- the position is set for the all new and existing g elements now. Complete example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With