How to use custom legends in NVD3 graphics

I am using the NVD3 line chart.

enter image description here

The default chart displays the legends that can be clicked.

I want to create a custom legend using the <ul>and elements <li>; clicking these <li>should toggle their respective lines on the chart.

$(function(){
    nv.addGraph(function() {
        var dayChart = nv.models.lineChart()
            .options({
                transitionDuration: 300,
                useInteractiveGuideline: true,
                interpolate: 'monotone'
            });

        dayChart.xAxis
            .axisLabel('Time')
            .tickValues([0, 1, 2, 3, 4])
            .tickFormat(function(d){
                return ["", "0-6", "6-12", "12-18", "18-24"][d]
            });

        dayChart.yAxis
            .axisLabel('Engagement')
            .tickFormat(function(d) {
                if (d == null) {
                    return 'N/A';
                }
                return d3.format(',d')(d);
            })
        ;

        var data = [
                {"values": [
                    { "x": 0 ,"y": 3 }, { "x": 1 ,"y": 5 }, { "x": 2 ,"y": 2 }, { "x": 3 ,"y": 4 }, { "x": 4 ,"y": 2 }],    "key": "Desktop","color":"#4b758d"
                }
                ,
                {"values": [
                    { "x":  0 ,"y": 1 },    { "x": 1 ,"y": 3 }, { "x": 2 ,"y": 4 }, { "x": 3 ,"y": 3 }],    "key": "Mobile","color":"#99c925"                },
                {"values": [
                    { "x": 0  ,"y": 2 },{"x": 1  ,"y": 4 }, { "x": 2 ,"y": 3 }, { "x": 3 ,"y": 5 }],"key": "Tablet","color":"#f23b71"                }
            ];

        d3.select('#line-chart').append('svg')
            .datum(data)
            .call(dayChart);

        nv.utils.windowResize(dayChart.update);

        return dayChart;
    });
});

Plunker for the full demo .

+4
source share
2 answers

To turn off the legend chart.showLedgend(false). Read more about how the whole code looks here .

Assuming you have a global instance of the chart, you need to change the state of the chart.

$(document).on('click', '#myButton', function(){
    chart.dispatch.changeState('key');
    chart.update();
});
+4
source

This works for me:

$(document).on('click', '#button', 
    function(){
        var state = chart.state;
        state.disabled[idOfItemInLegend] = !state.disabled[idOfItemInLegend];
        chart.dispatch.changeState(state);
        chart.update();
    }
);
0

Source: https://habr.com/ru/post/1614037/


All Articles