Dynamic Flot graph - show hide series by clicking on legend text or box on graph

后端 未结 2 976
挽巷
挽巷 2020-12-10 02:29

I am working on dynamic flot graph with 3 series. My need is to hide/show series when clicked on legend. I have seen different examples that will work fine for static graphs

相关标签:
2条回答
  • 2020-12-10 03:05

    Here's a quick example I put together for you.

    somePlot = null;
    
    togglePlot = function(seriesIdx)
    {
      var someData = somePlot.getData();
      someData[seriesIdx].lines.show = !someData[seriesIdx].lines.show;
      somePlot.setData(someData);
      somePlot.draw();
    }
    
    var data = [
        {
        label: 'foo',
        color: 'red',
        data: [[1, 300], [2, 300], [3, 300], [4, 300], [5, 300]],
          idx: 0},
    {
        label: 'bar',
        color: 'blue',
        data: [[1, 800], [2, 600], [3, 400], [4, 200], [5, 0]],
          idx: 1},
    {
        label: 'baz',
        color: 'yellow',
        data: [[1, 100], [2, 200], [3, 300], [4, 400], [5, 500]],
          idx: 2},
    {
        label: 'dart',
        color: 'green',
        data: [[1, 500], [2, 350], [3, 400], [4, 700], [5, 50]],
          idx: 3}
        ];
    
    somePlot = $.plot($("#placeholder"), data, {
        series: {
            lines: {
                show: true
            }
        },
        legend: {
            labelFormatter: function(label, series){
              return '<a href="#" onClick="togglePlot('+series.idx+'); return false;">'+label+'</a>';
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-10 03:06

    You can provide legend clicks in a way that survives rerendering the graph like so:

    HTML:

    <div id=graph></div>
    

    JS:

    $('#graph').on('click', 'div.legend tr', function() {
        var tr = $(this);
        var index = tr.parent().find('tr').index(tr);
        // Do something with the fact they clicked item (index)
    });
    

    There's nothing stored in the legend marking what each row represents, so you'll need to bring that info in from someplace else - all the above code does is get you the index of the legend item clicked.

    For usability you should tell the user this is clickable:

    CSS:

    #graph div.legend tr {
        cursor: pointer;
    }
    
    0 讨论(0)
提交回复
热议问题