将名称数组转换为线性比例d3

时间:2014-09-05 16:38:33

标签: javascript arrays d3.js

我有一组玩家列表的数据。我希望代表那些玩家的条形颜色可以在一系列颜色中变化。球员的名字显然是字符串,而不是数字...所以不知怎的,我需要说16个玩家转换为0到1的范围...所以第一个玩家最接近我阵列中的第一个颜色和最后一个玩家,到数组中的最后一种颜色。

我有一个颜色的例子,然后我制作了一个我的玩家的地图。我知道我很亲密,但不是那里。

var colors = ["gray","green","yellow","red"];

    var dtMap = dt.map(function(d){
        return d.Player;
    })

// was trying something like this
//var playaExtent = d3.scale.linear().domain(d3.extent(dtMap)).range([0,1]);
// trying to make a linear scale
// out of some names which are mapped above

var heatmapColor = d3.scale.linear()
                   .domain(dtMap)
                   .range(colors);

.attr("fill", function(d) {
         console.log(d.Player)
         return heatmapColor(d.Player)})

1 个答案:

答案 0 :(得分:0)

在下面的代码中,我使用polylinear scales将英文字母的24个字母映射到四种颜色的范围。输出( see demo )会产生彩虹色,同时打印字母和用于背景填充的数字的十六进制表示法。

因为我们正在使用线性刻度,所以基本思想是使用字母数组索引作为域的数字和数字的数字表示。

var colors = ['gray', 'green', 'yellow', 'red'],
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
    ratio = (alphabet.length - 1) / (colors.length - 1),
    scale = d3.scale.linear()
        // domain should be the same length as range in polylinear scales:
        .domain(colors.map(function (c, i) { return Math.round(i * ratio); }))
        // d3 automatically recognizes and interpolates color strings:
        .range(colors);

d3.select('#container').data(alphabet, function (d) { return d; })
    .enter().append('div')
        .text(function (d, i) { return d + ' ' + scale(i); })
        .style('background-color', function (d, i) { return scale(i); });

可以随意更改字母表中的颜色和字母数。在4个字母和4种颜色的情况下,程序将输出精确的映射:灰色" a",绿色" b",黄色" c"和红色" d&#34 ;.