1

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!

2
  • can you clarify your goals? In the example you gave it makes more sense to simply use your own function directly instead of a D3 scale Commented Jun 18, 2014 at 16:14
  • This question is answered in the API documentation. Commented Jun 18, 2014 at 18:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.