flot graph, use legend to turn on/off series

Matt Heffernan picture Matt Heffernan · Nov 20, 2010 · Viewed 16.3k times · Source

I want to be able to use the legend of a flot graph to turn on/off the series of my graph. I found the examples on the flot site and have used the Turning series on/off and Labelformatter from the API to build what I have right now. I can put checkboxes next the legend elements and add a click event to them and its fires. But that calls the plot function again and resets my checkbox values. I have included the full jquery function, sorry its a bit long.

<script id="source">
var jsonPath = "JsonPriceHistory/" + getParameterByName("CardId")



$(function () {
    $.getJSON(jsonPath, function (results) {

        results = [{ "label": "A", "data": [[1290115114240, 0.7000], [1289396258877, 0.7000], [1289394738247, 0.7000], [1288482602563, 0.7000], [1288479321830, 0.7000], [1288464257267, 0.7000], [1288463414413, 0.7000], [1268440264933, 1.0000], [1268434766653, 1.0000], [1268059707567, 1.0000], [1265934534340, 1.0000]] }, { "label": "B", "data": [[1290115102033, 6.0000], [1289395956947, 6.0000], [1289394743117, 6.0000], [1288482613967, 6.0000], [1288479332767, 6.0000], [1288464270420, 6.0000], [1288463427313, 6.0000], [1268440276413, 6.0000], [1268434778203, 6.0000], [1268059732683, 6.0000], [1265934545390, 6.0000]] }, { "label": "C", "data": [[1290115034640, 0.3000], [1289397347113, 0.3000], [1289396593083, 0.3000], [1289395047560, 0.3000], [1288484556080, 0.3000], [1288482794357, 0.3000], [1288465863503, 0.3000], [1288465248087, 0.3000], [1288464674300, 0.3000], [1268470601960, 0.6000], [1268469438957, 0.6000], [1268468281610, 0.6000], [1268440646800, 0.6000], [1265984810360, 0.8000], [1265955747730, 0.8000]] }, { "label": "C", "data": [[1290115031727, 0.1200], [1289397678960, 0.1200], [1289397337040, 0.1200], [1289396577510, 0.1200], [1289395024607, 0.1200], [1288484550417, 0.1200], [1288482780457, 0.1200], [1288465846327, 0.1200], [1288465231287, 0.1200], [1288464658213, 0.1200], [1268470586860, 0.2000], [1268469423697, 0.2000], [1268468266277, 0.2000], [1268440631390, 0.2000], [1265984774793, 0.2000], [1265955732580, 0.2000]] }, { "label": "D", "data": [[1290114958773, 0.0500], [1289397467207, 0.0500], [1289396747243, 0.0500], [1289395166640, 0.0500]] }, { "label": "E", "data": [[1290114933540, 0.6500], [1289397579447, 0.6500], [1289397242333, 0.6500], [1289396486657, 0.6500], [1289395003947, 0.6500], [1288484568590, 0.6500], [1288482784747, 0.6500], [1288465893750, 0.6500], [1288465278320, 0.6500], [1288464705170, 0.6500], [1268470629373, 0.6500], [1268469467810, 0.6500], [1268468309513, 0.6500], [1268440674610, 0.6500], [1265984889857, 0.6500], [1265955775453, 0.6500]] }, { "label": "F", "data": [[1290114885570, 0.1100], [1289396731507, 0.1100], [1289395170397, 0.1100]]}];

        var options = {
            legend: {
                show: true,
                container: $("#overviewLegend"),
                labelFormatter: function (label, series) {
                    var cb = '<input type="checkbox" name="' + label + '" checked="checked" id="id' + label + '"> ' + label;
                    return cb;
                }
            },
            series: {
                points: { show: true },
                lines: { show: true }
            },
            grid: { hoverable: true },
            xaxis: {
                mode: "time",
                minTickSize: [1, "day"],
                max: new Date().getTime()
            },
            yaxis: {
                mode: "money",
                min: 0,
                tickDecimals: 2,
                tickFormatter: function (v, axis) { return "$" + v.toFixed(axis.tickDecimals) }

            }
        };

        var i = 0;
        $.each(results, function (key, val) {
            val.color = i;
            ++i;
        });

        var choiceContainer = $("#overviewLegend");

        function plotAccordingToChoices() {
            var data = [];
            alert('hi');

            choiceContainer.find("input:checked").each(function () {
                var key = $(this).attr("name");
                if (key && results[key])
                    data.push(results[key]);
            });

            $.plot($("#placeholder"), results, options);
            choiceContainer.find("input").click(plotAccordingToChoices);
        }



        var previousPoint = null;
        $("#placeholder").bind("plothover", function (event, pos, item) {
            $("#x").text(pos.x.toFixed(2));
            $("#y").text(pos.y.toFixed(2));

            if (item) {
                if (previousPoint != item.datapoint) {
                    previousPoint = item.datapoint;

                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(2);

                    showTooltip(item.pageX, item.pageY, item.series.label + " $" + y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;
            }
        });

        function showTooltip(x, y, contents) {
            $('<div id="tooltip">' + contents + '</div>').css({
                position: 'absolute',
                display: 'none',
                top: y + 5,
                left: x + 15,
                border: '1px solid #fdd',
                padding: '2px',
                'background-color': '#fee',
                opacity: 0.80
            }).appendTo("body").fadeIn(200);
        }

        plotAccordingToChoices();
    })



});

Answer

Yi Jiang picture Yi Jiang · Nov 20, 2010

There's a couple of problem with your code:

The data you're using is in the form of an array, while the one presented in the demo is an object. The distinction is important here because you've copied their code, but did not change the code to accommodate this. The lines in question are:

if (key && results[key])
    data.push(results[key]);

inside the plotAccordingToChoices() function. results[key] in your case would not work because key would need to be a numerical value, but key here is a string. The solution is to replace this with a for loop which searches through the array for the correct label:

for (var i = 0; i < results.length; i++) {
    if (results[i].label === key) {
        data.push(results[i]);
        return true;
    }
}

Next, the problem is that you are replotting the same data over and over again, with this line:

$.plot($("#placeholder"), results, options);

results[] never changes - you should be using data[] here instead:

$.plot($("#placeholder"), data, options);

Then, unlike in the demo, you've decided to setup the checkboxes using the formatlabel function in the legend option when plotting the graph. The problem with this is that when you replot the graph with new data that does not contain all of the results, the checkboxes for the unplotted lines will not show up because flot will not plot the labels of non-existent lines.

This means that you will have to do as the demo does - to create the checkboxes separately. We do this by adding the following lines to the $.each loop that is used to fix the colors each line uses:

l = val.label;
var li = $('<li />').appendTo(choiceContainer);

$('<input name="' + l + '" id="' + l + '" type="checkbox" checked="checked" />').appendTo(li);
$('<label>', {
    text: l,
    'for': l
}).appendTo(li);

This will create a checkbox - label set for each set of data in the results array. Finally we move the function for binding plotAccordingToChoices to each checkbox outside the function, so that the binding only occurs once, to prevent multiple bindings and the resultant mess:

choiceContainer.find("input").change(plotAccordingToChoices);

We also change it to use the change event instead of click because change here is more appropriate.

And finally, as a bonus, we loop through the legend table and pull the colors from there to add to the list of checkboxes:

$('.legendColorBox > div').each(function(i){
    $(this).clone().prependTo(choiceContainer.find("li").eq(i));
});

We also need a little CSS for this to work:

#overviewLegend li > div {
    display: inline-block;
    margin-right: 4px;
}

See the final working code live here: http://jsfiddle.net/yijiang/6FLsM/2/