morrisjs / morris.js

Pretty time-series line graphs
http://morrisjs.github.com/morris.js/
6.92k stars 1.23k forks source link

add and toggle legend item to show or hide data series #775

Open mohd7469 opened 5 years ago

mohd7469 commented 5 years ago

could somebody tell how to hide/unhide data series on legend items click in Morris Line graph ?

pierresh commented 5 years ago

Hello,

you could set an array variable for the ykeys populated with the default ykeys.

Then when you click on legend items, it add/remove the associated ykey (i.e. in data attribute), then you update the ykeys options of Morris, then call the method .redraw()

mohd7469 commented 5 years ago

@pierresh thanks for getting replied, can you show a basic example please, because i think i am doing the same

image

pierresh commented 5 years ago

Hello,

I just updated my fork to make this easier. A class per index is now added to line and circles. Then just just need to hide/display them when clicking on the legend.

Here below is working example: Javascript

<script>
    var tmp_array = ['nb', 'a'];
    Morris.Line({
        element: 'chart_line_1',
        data: [
            {year: '1958', nb: 1, a: 2},
            {year: '1962', nb: 2, a: 2},
            {year: '1970', nb: 3, a: 2},
            {year: '1994', nb: 4, a: 2},
            {year: '2002', nb: 5, a: 2},
        ],
        xkey: 'year',
        ykeys: tmp_array,
        dataLabels: false,
        labels: ['Editions Wins', 'Line 2']
    }).options.lineColors.forEach(function(color, a){ 
    if (tmp_array[a] != undefined) {
        $('#chart_line_1').parent('div')
                            .find('div.legend')
                            .append($('<span data-index="'+a+'">'+tmp_array[a]+'</span>')
                            .css('color', color));
        }
    });

    $('div.legend').on('click', 'span', function(){
        var index = $(this).data('index');
        if ($('#chart_line_1 path.line_'+index).hasClass('hidden')) {
            $('#chart_line_1 path.line_'+index).removeClass('hidden');
            $('#chart_line_1 circle.circle_line_'+index).removeClass('hidden');
        } else {
            $('#chart_line_1 path.line_'+index).addClass('hidden');
            $('#chart_line_1 circle.circle_line_'+index).addClass('hidden');
        }
    });
</script>

HTML

<div>
    <div id='chart_line_1' class='chart_morris'></div>
    <div class='legend'></div>
</div>

CSS

<style>
    .hidden { display:none!important; }
</style>