I know the question is about R and 4 years old, but I ran into this same need in JavaScript. I put together an implementation of this for my own JS, thought others might be interested.
In my case, I'm displaying historical data for a device (voltage, current, etc).
Part of that involves building a readable title for the graph, such as "Generator 1: Voltage, Current". the data
array contains all my results, and the property
of each dataset is the readable title. When I am looping through to build my main title I do this:
var thistitle = data[i].property;
var thislink = `<a href="#" onclick="HV3_toggleVis(${i})">${thistitle}</a>`
var visArray = [];
for(var i=0;i<data.length;i++) { //for each requested dataset
visArray.push(true); //build out boolean visibility array
}
When I build my graph, i do:
window.dygraphs.history_output = new Dygraph([...]);
window.dygraphs.history_output.visArray = visArray;
Now my array of booleans for each dataset is stored as a property of my graph object.
When I build my title, I do:
var thistitle = data[i].property;
var thislink = `<a href="#" onclick="HV3_toggleVis(${i})">${thistitle}</a>`
titles[data[i].name].titlestring += thislink;
Now I have an array of links for running my visibility toggles.
For my function, i have:
function HV3_toggleVis(seriesIndex) {
var visArray = window.dygraphs.history_output.visArray; //i like short working names for vars.
visArray[seriesIndex] = !visArray[seriesIndex]; //toggle boolean
window.dygraphs.history_output.setVisibility(seriesIndex,visArray[seriesIndex]); //toggle the selected dataset
window.dygraphs.history_output.visArray = visArray; //save the changes to the object
}
In future I might try to put it in the legend instead, but for now this is lovely.
Here's an example of it in action. I haven't copied it over to my live unit yet, so the dataset is just a line, but you get the idea:
https://i.imgur.com/K3mq0oA.png