javascriptjqueryarraysfunctionjscharts

How to generate random color for JSCharts


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

I'm using JSCharts in a project I'm working on and I need a different color for each bar in a Graph/Bar Chart.

the below example works fine but if I have more than 6 records then it alert me a message:

JSChart" Colors array length must equal data length in case of pie and bar graphs

How can I generate color based on the number of records?

Here's an example of the bar chart data set:

$.getJSON("http://...", function (data) {

        var array = $.map(data, function (data) {
            return [[data.Name, parseInt(data.Id)]];
        }); 

        var colors = ['#FA5E1F', '#FDCB3F', '#71D743', '#D23333', '#BAE73F', '#B381C9'];
        var myChart = new JSChart('graph', 'bar');
        myChart.setDataArray(array);
        myChart.colorizeBars(colors);
        myChart.setTitle('Title');
        myChart.setTitleColor('#8E8E8E');
        myChart.setAxisNameX('Orgs');
        myChart.setAxisNameY('%');
        myChart.setAxisColor('#c6c6c6');
        myChart.setAxisWidth(1);
        myChart.setAxisNameColor('#9a9a9a');
        myChart.setAxisValuesColor('#939393');
        myChart.setAxisPaddingTop(60);
        myChart.setAxisPaddingLeft(50);
        myChart.setAxisPaddingBottom(60);
        myChart.setTextPaddingBottom(20);
        myChart.setTextPaddingLeft(15);
        myChart.setTitleFontSize(11);
        myChart.setBarBorderWidth(0);
        myChart.setBarSpacingRatio(50);
        myChart.setBarValuesColor('#737373');
        myChart.setGrid(false);
        myChart.setSize(616, 321);
        //myChart.setBackgroundImage('chart_bg.jpg');
        myChart.draw();
    });

Solution

  • Your function looks good! To use it to generate colors in an array, just use a loop:

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

    Then, you can get your data length by using the Array.length property. Replace these lines:

    var colors = ['#FA5E1F', '#FDCB3F', '#71D743', '#D23333', '#BAE73F', '#B381C9'];
    var myChart = new JSChart('graph', 'bar');
    myChart.setDataArray(array);
    myChart.colorizeBars(colors);
    

    with:

    var myChart = new JSChart('graph', 'bar');
    myChart.setDataArray(array);
    myChart.colorizeBars(getColorArray(array.length));