You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Google Charts饼图如何实现真正的随机颜色

Fixing Random Colors in Google Charts Pie Chart

Hey there! I see you're stuck trying to get fully random colors for your Google Charts Pie Chart—let's figure this out together.

Why Your Current Code Isn't Working

The key issue here is that when you define a colors array in your options, Google Charts completely ignores the useRandomColors: true setting. It prioritizes your predefined color list first, which is why your pie slices keep following the yellow → red → blue order you set.

Solution: Generate Custom Random Colors

Instead of relying on the (somewhat limited) useRandomColors flag, we can build a simple function to generate totally random hex colors, then dynamically populate the colors option with these values. Here's your updated code:

<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);

// Helper function to create a random hex color
function getRandomColor() {
  const hexChars = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += hexChars[Math.floor(Math.random() * 16)];
  }
  return color;
}

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

// Generate enough random colors for each data entry
const colorCount = data.getNumberOfRows();
const randomColors = [];
for (let i = 0; i < colorCount; i++) {
  randomColors.push(getRandomColor());
}

var options = {
title: 'Test',
colors: randomColors, // Use our dynamically generated random colors
};

var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>

How This Works

  1. The getRandomColor() function creates a unique 6-character hex color (like #2D78B3 or #F9C80E) every time it's called.
  2. We count how many data rows you have (excluding the header) using data.getNumberOfRows().
  3. We loop that number of times to generate a matching set of random colors, then assign this array to the colors option.

Now every time you refresh the page, your pie chart will have a brand new set of totally random colors—no fixed list holding you back!

If you want to avoid overly similar colors (e.g., too many dark or light shades), you could tweak the getRandomColor() function to restrict values for brighter/darker hues, but this basic version should perfectly meet your "fully random" requirement.

内容的提问来源于stack exchange,提问作者Nina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:23:25