sorting - D3 sort() with CSV data -


i trying kinds of ways make .sort() work on csv dataset. no luck.

for starts, i'd sort data "value" column.

this function i'm running inside d3.csv api call , before select dom , append divs:

dataset = dataset.sort(function (a,b) {return d3.ascending(a.value, b.value); }); 

before .sort, clean data:

dataset.foreach(function(d) {             d.funded_month = parsedate(d.funded_month);             d.value = +d.value;         });         }; 

everything seems in order. when console.log(d3.ascending(a.value, b.value)), right outputs:

-1 d32.html:138 1 d32.html:138 -1 d32.html:138 1 d32.html:138 etc.. 

yet bars data doesn't sort.

what's wrong?

it not clear provided code hazard guess not handling async nature of d3.csv.

this plunkr shows sort code working fine. note data object declared, populated, , used.

here partial listing. have added buttons re-order data. achieve need put ordering logic inside render rather inside d3.csv callback.

<script type="text/javascript"> var data = []; d3.csv("data.csv",         function(error, rows) {             rows.foreach(function(r) {                 data.push({                     expense: +r.expense,                     category: r.category                 })             });             render();         });  function render(d3comparator) {     if(d3comparator) data = data.sort(function(a, b) {         return d3[d3comparator](a.expense, b.expense);     });     d3.select("body").selectall("div.h-bar") // <-b             .data(data)             .enter().append("div")             .attr("class", "h-bar")             .append("span");     d3.select("body").selectall("div.h-bar") // <-c             .data(data)             .exit().remove();     d3.select("body").selectall("div.h-bar") // <-d             .style("width", function(d) {                 return (d.expense * 5) + "px";             })             .select("span")             .text(function(d) {                 return d.category;             }); }  </script>  <button onclick="render('ascending')">sort ascending!</button> <button onclick="render('descending')">sort descending!</button> 

Comments

Popular posts from this blog

C# random value from dictionary and tuple -

cgi - How do I interpret URLs without extension as files rather than missing directories in nginx? -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -