Automatic Colors Assignment In Chart.js 2.x Doesn't Work Anymore, Used To Work In V. 1.x


Answer :

I believe that creation of color schemes is a whole science of its own. It makes sense to me that something like that has been left out of Chart.js, since there are more critical goals to pursue.

All colors used in chart examples in the docs are defined explicitly. And this two-month-old issue features a categorical response from a Chart.js member that default colors are not available in Chart.js 2.

So, you have three choices.

  • The first choice is to make some colors yourself. I guess you would not have asked the question, had you been into something like that (I know that the results would be horrible, if I did something like that).

  • The second choice is to look for color schemes and color scheme generators online and pick some color schemes that please you.

  • The third and interesting choice is to look for a JavaScript library that can produce color schemes at will.

There are a couple of alternative choices. A nice one, which is available under very permissive licensing, is the Colour Palette Generator. You may see it in action along Chart.js 2 here. The sample is also available below:

var ctx = document.getElementById("myChart"); var myData = [12, 19, 3, 5, 2, 3]; var myChart = new Chart(ctx, {   type: 'pie',   data: {     labels: ["First", "Second", "Third", "Fourth", "Fifth", "Sixth"],     datasets: [{       label: '# of Votes',       data: myData,       backgroundColor: palette('tol', myData.length).map(function(hex) {         return '#' + hex;       })     }]   } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script> <script src="https://raw.githubusercontent.com/google/palette.js/master/palette.js"></script> <canvas id="myChart" width="400" height="400"></canvas>

How to use the library is described here. In short, you may create a 10-color palette from a specific color scheme using the following:

var seq = palette('tol-sq', 10); 

The result is an array of hex strings (e.g. "eee8d5"). In order to use it where Chart.js is expecting colors, you may use map to prepend "#" to each string, like in the example above.


I would actually recommend ChartsJS-Plugin-ColorSchemes. Simply importing it after chartjs will be enough for you to have automatic coloring but adding options will allow you to make custom palettes, for example.

...    options: {      plugins: {        colorschemes: {          scheme: 'tableau.Tableau20'        }      }    } 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?