Random fill colors in Chart.js

16,116

Solution 1

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

Then set:

fillcolor = getRandomColor()

Solution 2

I am afraid there just is no in-built function in chart.js library for doing this. And what is the harm in defining your own javascript function anyways?

The implementation would look pretty much similar to what you are looking for, except that you would have defined what barColor() would do yourself.

If you haven't found them already, there are a couple of great solutions here. (using JavaScript functions)

Share:
16,116
Aditya Chaudhary
Author by

Aditya Chaudhary

I am a B.Tech Computer Science graduate currently working as a Cyber Security Analyst.

Updated on July 18, 2022

Comments

  • Aditya Chaudhary
    Aditya Chaudhary almost 2 years

    I have been using nvd3 for a long time. In nvd3 we have an option to specify automatic graph fill colors.

    chart.barColor()
    

    How can I fill random colors in Chart.js graphs without defining each color in datasets?

    I don't want to use JavaScript function to generate and get random colors from it. I need something similar to nvd3 barColor()

    If there is a possible way, then please help me out.

  • Aditya Chaudhary
    Aditya Chaudhary almost 9 years
    Thank you very much for you answer. The problem I have is that I have no fixed quantity that how many bars (taking example of bar-graph) could be there in the graph. So I can not define a fixed number of colors.
  • Swanky Coder
    Swanky Coder almost 9 years
    In that case... what you can do is write a function which generates colors randomly starting from a selected color, not repeating the colors. I can edit my answer accordingly if you'd like :)
  • N. Ivanov
    N. Ivanov almost 7 years
    OP has specifically asked that he does not want a function that randomly generates colors.
  • Kanabos
    Kanabos about 6 years
    It is useful despite the question didn't asked for that.