My Javascript skills are fairly basic but advanced enough to get me to a position where I am able to design some relatively complex charts using the d3 library. I've now got to the point where I am looking to make some of my code reusable and this is where I've come across the first hurdle that the excellent api documentation can't get me past.
As an example, in the majority of my charts I want to add a legend. I have some basic code that adds a svg group for the legend which looks like this
var legend = chartContainer.selectAll(".legend")
.data(d3.map(data, function(d){return d.FIELDNAME;}).keys())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });
what I'd like to be able to do is add a parameter to a function which allows me to set what field from the dataset is used in the legend. Something like the below... but that actually works :)
function addLegend(legendKey) {
var legend = chartContainer.selectAll(".legend")
.data(d3.map(data, function(d){return d.legendKey;}).keys())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });
// rest of the legend code
}
called by
addLegend("FIELDNAME");
Lastly, understandably (perhaps) this didn't work either
function helper(legendKey){
return legendKey;
}
function addLegend(helper) {
var legend = chartContainer.selectAll(".legend")
.data(d3.map(data, function test (d, addLegend){return d.addLegend;}).keys())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });
// rest of the legend code
}
addLegend(helper("agent"))
Any help would be greatly appreciated.