Reputation: 594
I was wondering if it is possible to use functions within d3.js functions. To clarify my question, let's assume you have a colorscale
var colorScale = d3.scale.quantile()
.domain([0,8])
.range(["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]);
Is there a way to make the following work?
var colorScale = d3.scale.quantile()
.domain([0,8])
.range(function(){return ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]});
so returning the entire argument from a function?
many thanks to anyone who knows!
Upvotes: 1
Views: 727
Reputation: 594
Thank you Explunit, Lars and Thomas
I have found an adequate answer to my question though.
The answer is: yes it's possible and here is how if you know the argument to your range is going to be a function:
var myfunction = function()
{return ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]}
var colorScale = d3.scale.quantile()
.domain([0,8])
.range(myfunction());
If however you are not sure. you can use the d3.functor() which will work even if you pass it a value and not a function. So like this (if it's a function):
var myfunction = function()
{return ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]}
var myfunctionWrapped = d3.functor(myfunction);
var colorScale = d3.scale.quantile()
.domain([0,8])
.range(myfunctionWrapped());
And like this if it is a value (or array):
var myfunction = ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]
var myfunctionWrapped = d3.functor(myfunction);
var colorScale = d3.scale.quantile()
.domain([0,8])
.range(myfunctionWrapped());
So I would recommend using the d3.functor() since it makes your code more versatile.
Upvotes: 2
Reputation: 14063
Not with ranges. Although many other d3 methods allow functions as parameters. Those are generally methods which are likely to return different values based on a specific datum.
Upvotes: 1