flot graph, use legend to turn on/off series

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/

Leave a Comment