1
votes

I'm new so i'm not so good and my english is not so good (sorry >o<). I'm in training and for short, I have to make a google chart pie with random colors. I searched for a lot of solutions on the internet, but the only one I found and understood is this:
colors:['yellow', 'red', 'blue', 'green', 'violet', 'pink'], useRandomColors: true,

But that does not correspond to what I want, on the one hand, the colors do not put themselves absolutely randomly and then, this property is useless. Here is my test code(because we are working with data from a database and not with raw data as in this example):


  <head>
    <script type="text/javascript"src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     2],
      ['Eat',      4],
      ['Commute',  5],
      ['Watch TV', 8],
      ['Sleep',    9],
    ]);

    var options = {
      title: 'Test',
      colors:['yellow', 'red', 'blue', 'green', 'violet', 'pink'],
      useRandomColors: true,
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }
  </script>
 </head>
<body>


enter image description here

Here is an image, we see the colors in the order in which I put them, it does not help me.

If a charitable soul can help me, I would be very grateful to him.

1

1 Answers

-1
votes

I think you should try to shuffle the array before using it. Here is a link to the answer on how to do it.

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

// Used like so
var arr = ['yellow', 'red', 'blue', 'green', 'violet', 'pink'];
arr = shuffle(arr);