我想知道是否可以在d3.js函数中使用函数。 为了澄清我的问题,让我们假设你有一个色阶
var colorScale = d3.scale.quantile()
.domain([0,8])
.range(["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]);
有没有办法让以下工作?
var colorScale = d3.scale.quantile()
.domain([0,8])
.range(function(){return ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]});
所以从函数返回整个参数?
非常感谢任何知道的人!答案 0 :(得分:2)
谢谢Explunit,Lars和Thomas
我已经找到了对我的问题的充分答案。
答案是:是的,这是可能的,如果你知道你的范围的论证将成为一个函数,那么这就是:
var myfunction = function()
{return ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]}
var colorScale = d3.scale.quantile()
.domain([0,8])
.range(myfunction());
但是如果你不确定的话。你可以使用d3.functor(),即使你传递一个值而不是一个函数,它也会工作。所以这样(如果它是一个函数):
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());
如果它是一个值(或数组),就像这样:
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());
因此我建议使用d3.functor(),因为它使您的代码更加通用。
答案 1 :(得分:1)
不是范围。虽然许多其他d3方法允许函数作为参数。这些通常是基于特定数据可能返回不同值的方法。