使用固定颜色集来显示散点图

时间:2016-03-24 01:16:58

标签: javascript d3.js c3.js

我有一个随机颜色功能,可以为散点图中的每个绘图生成不同的颜色。

function getRandomColor() {
                            var letters = '0123456789ABCDEF'.split('');
                            var color = '#';
                            for (var i = 0; i < 6; i++) {
                                color += letters[Math.floor(Math.random() * 16)];
                            }
                            return color;
                        }

但是我怎样才能为这些情节提供固定的颜色集?

回复更新:

 var colors = ['red','green','blue','#2A0A0A','#00FF40','#8A4B08',"#610B21","#0A2229","#5E610B","#3B0B2E","#FF0040","#B43104","#0B6121","#01DFA5","#2E2EFE","#DF01A5","#088A4B","#B40431","#1C1C1C","#B45F04"];


    type: 'scatter',
    color: function (color, d) {
        return colors[d.index];
        },

1 个答案:

答案 0 :(得分:1)

根据the documentation,颜色函数可以接收两个参数,第一个是基色(不知道此时它来自何处),以及一个保存该点数据的对象(包括索引) )。您可以使用此信息从十六进制颜色字符串数组中确定所需的颜色。

示例:

var colors = ['#1f77b4','#aec7e8','#ff7f0e','#ffbb78'];
...
c3.generate({
data: {
    color:function(color, data){            
        return colors[data.index%colors.length];
        //Example way of picking out your colors from a fixed array
    },
...}