Reputation: 531
I am trying to slightly change the behavior of nvd3 horizontal chart.
Right now the horizontal chart has a legend with possible option to have multiple legend items selected at the same time. I'm just trying to show only one item at a time so that when one series is selected, others are deselected.
var data = [
{
"key": "Series1",
"color": "#d62728",
"values": [
{
"label" : "A" ,
"value" : 1
} ,
{
"label" : "B" ,
"value" : 8
} ,
]
},
{
"key": "Series2",
"color": "#1f77b4",
"values": [
{
"label" : "C" ,
"value" : 25
} ,
{
"label" : "D" ,
"value" : 16
} ,
]
}
]
nv.addGraph(function() {
var chart = nv.models.multiBarHorizontalChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.margin({top: 30, right: 20, bottom: 50, left: 175})
.showValues(true)
.tooltips(false)
.showControls(false);
chart.yAxis
.tickFormat(d3.format(',.2f'));
d3.select('#chart svg')
.datum(data)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
And I also modified the multiBarHorizontalChart portion of nv.d3.js with the following on lines 6264 to 6272:
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
data.map(function(d,i){
d.disabled= true;
return d;
});
This makes it so that it behaves like radio buttons, however when the chart is first loaded, both Series1 and Series2 are visible.
So my question is "how would you make only one series visible?"
Upvotes: 2
Views: 2108
Reputation: 6305
I had the same problem and ended up creating a patch which solves this in, I believe, a cleaner way against the latest version. You can follow the issue & pull request here:
https://github.com/novus/nvd3/issues/168
Upvotes: 1
Reputation: 531
I ended up replacing
var barsWrap = g.select('.nv-barsWrap').datum(data.filter(function(d, i) {return !d.disabled }))
in the nv.d3.js file with the following:
var all_undefined = true;
for (var i=0; i < data.length; i++){
if (data[i].disabled === true || data[i].disabled === false){
all_undefined = false;
}
}
if (all_undefined){
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d, i) {
if (i===0){
wrap.selectAll('.nv-series').classed('disabled', true);
wrap.select('.nv-series').classed("disabled", false);
return !d.disabled
}
}))
}
else{
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d, i) {return !d.disabled }))
}
Not a very elegant solution, but it works to make radio buttons from the legend in the horizontal bar chart.
Upvotes: 2