javascript - How to sort a D3 bar chart (based on an array of objects) by value or key? -


i new d3 , javascript in general , i'm trying wrap head around possible interactions rather simple bar charts.

what trying achieve:

i have option sort bar chart value when click on 1 of bars , alphabetically keys if click once more.

my progress far:

my bar chart based on array of objects keys names of companies , values indicate mean satisfaction each company on scale 0 100.

var data = [     {key: "test 1",  value: 21},     {key: "test 2",  value: 34},     ...     {key: "test 12", value: 22},     {key: "test 13", value: 97} ]; 

you can see progress , whole code here: bl.ocks.org

i attempted create function sort array. i'm pretty lost on how reposition bars since bars positioned based on key , don't know how else on ordinal scale.

var x = d3.scaleband()     .domain(data.map(function(d){         return d.key;     }))     .range([margin.left, width])     .padding(0.1);   var y = d3.scalelinear()     .domain([0, d3.max(data, function(d){         return d.value;     })])     .range([height, margin.top])    var sortbars = function(){  svg.selectall("rect")     .sort(function(a,b){         return b.value-a.value;           })     .transition("sort")     .duration(100)     .attr("x", function(d,i){         return x(d.key);     })    } 

at first thought if sort array, return value based on key should based on new order, doesn't seem work.

thank in advance tips or help!

a simple way sorting data array, , recalculating domain. key:

data.sort(function(a, b) {   return d3.ascending(a.key, b.key) }) x.domain(data.map(function(d) {   return d.key; })); 

and value:

data.sort(function(a, b) {   return d3.descending(a.value, b.value) }) x.domain(data.map(function(d) {   return d.key; })); 

here bl.ocks changes, put 2 buttons: https://bl.ocks.org/anonymous/bc5a9691a3417b403d4e8ade3297afa3/3a2434c1c2849e476791e581754ec27e055db4d6

ps: have in mind sorting key sorting strings. therefore, "test 2" comes after "test 13". if want sequence "test 1", "test 2", "test 3" etc, you'll have modify strings.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -