Question

I'm a n00b and having trouble with NVD3, and there're some smart people on here, so I hope you can help.

I'm trying to create a drop box that will select data to display. I can call a function with but I cannot get the chart to change its data location.

HTML:

<select name="slct" id="name" onchange="data(this.value)">
<option>Select power data</option>
<option value="Residence_supply_data">Average kwh residences supplied to the grid</option>
<option value="Residence_need_data">Average kwh supplied to residences</option>
</select>

NOTE: I've created JSON libraries with the values above as names.

Javascript:

function data(value) {
    console.log(value);
    var dat_select = value;
    return dat_select;
};

var chart;
nv.addGraph(function() {
    chart = nv.models.multiBarHorizontalChart().x(function(d) {
        return d.label
    }).y(function(d) {
        return d.value
    }).margin({
        top : 30,
        right : 105,
        bottom : 30,
        left : 100
    })
    //.showValues(true)
    .tooltips(true).barColor(d3.scale.category20().range()).showControls(false);

    chart.yAxis.tickFormat(d3.format(',.0f'));

    d3.select('#chart1 svg').datum(dat_select).transition().duration(1000).call(chart);

    nv.utils.windowResize(chart.update);

    chart.dispatch.on('stateChange', function(e) {
        nv.log('New State:', JSON.stringify(e));
    });

    return chart;
});

Everything works otherwise, and the function logs the results, just can't select the data I need to. If I set d3.select('#chart1 svg').datum(Residence_supply_data), it loads that data.

You have my gratitude.

Was it helpful?

Solution

At the point where d3.slect('#chart1 svg') assign it to a variable(global variable)

myChart = d3.select('#chart1 svg').datum(dat_select).transition()
            .duration(1000).call(chart);

So now myChart contains the nvd3 multiBarHorizontalChart() chart.

So when you want the chart updated by calling a function updateMyChart() for example from a place of your choice you could update it like this :

function updateMyChart() {
    // myChart is passed to your new data
    // myChart also calls chart which hold the attributes you 
    // had set earlier for multiBarHorizontalChart
    myChart.datum(Residence_supply_data).transition().duration(1000).call(chart);

    // Update the chart during the window screen resizing
    nv.utils.windowResize(myChart.update);
}

Hope this helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top