kodisha kodisha - 10 months ago 40
Javascript Question

Is it possible to select multiple bars on bar chart in d3.js with mouse

I was trying to google for this, but no luck.

What i want is to take standard bar chart in d3.js, for example like this


and select with my mouse middle 4 bars, and somehow get value of selected values only.

Is such thing possible with d3?

I think my question might be bit misleading, I don't want to do multiple clicks to select objects, i want to click and drag once and select underlying objects, see sencha example in my comment.


d3.brush is the answer, you can see the working demo here

Answer Source

You can implement this using the .on() function and the click event. See the documentation. To be able to select multiple bars, you would need to keep track of the current selection in a global variable, for example an array that is added to and removed from as you click on unselected/selected bars. The code might look something like

var selection = [];
var bars = vis.selectAll("g.bar")
    .on("click", function(d) {
        if(selection.indexOf(d) == -1) { selection.push(d); }
        else { selection.splice(selection.indexOf(d), 1); }