简体   繁体   中英

D3.js - Updating Bar Chart Data with buttons

So I've been trying to get my d3.js bar chart to transition to different values when a button is pressed. Though, at the moment some elements seem to be adding, but extremely wide and all over the place, as well as the previous elements not being removed.

This is my code:

function updateData(time) {

timeValue = time;


// Get the data again
d3.tsv(timeValue + ".tsv", function(error, data) {
  x.domain(data.map(function(d) { return d.letter; }));
  y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
// Scale the range of the data again 
x.domain(d3.extent(data, function(d) { return d.letter; }));
y.domain([0, d3.max(data, function(d) { return d.frequency; })]); 

//Selecting Data
var bars = svg.selectAll("rect")
         .data(data);


//Removing
bars.exit().remove("rect");

//Changes
bars.enter().append('rect')
.attr("class", "bar")
bars.attr('x', function(d) { return x(d.letter); })
.attr('width', x.rangeBand())
.attr('y', function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); }); 
 //var svg = d3.select("div.innerScreen2").transition();        
}); 

Now I've looked at similar questions asked and tried to apply the solutions, but nothing seems to get removed or change :/ Maybe I have code in the wrong place? Any help would be much appreciated

There are two problems to solve in your question. The first issue is related to the update pattern that some elements are added and some not. Do you have an unique identifier in your data set? If yes, you can use a function within the update process:

// Join new data with old elements, if any.
var text = svg.selectAll("text")
      .data(data, function(d) { return d.id; });

Source: http://bl.ocks.org/mbostock/3808234

The second issue is related to your x/y positions and may depend on your underlying data. An data excerpt or debugging information are required to solve this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM