2015-03-03 145 views
4

我正在嘗試使用Chart.js繪製餅圖。我的值來自數據庫,因此我不知道數據庫中會有多少值。在這裏我想設置爲每個值設置一個唯一的顏色。以下是我的例子。如何將顏色族設置爲chart.js中的餅圖

var pieData = [ 
    { 
     value: 20, 
     color:"#878BB6" 
    }, 
    { 
     value : 40, 
     color : "#4ACAB4" 
    }, 
    { 
     value : 10, 
     color : "#FF8153" 
    }, 
    { 
     value : 30, 
     color : "#FFEA88" 
    } 
]; 

var pieOptions = { 
    segmentShowStroke : false, 
    animateScale : true 
} 

var countries= document.getElementById("countries").getContext("2d"); 
     new Chart(countries).Pie(pieData, pieOptions); 

目前在上面的例子中我已經設置硬編碼值,但在我的示例數據(JSON)從DB到來。

回答

4

你可以循環思考你的pieData數組並設置顏色值的隨機值。

你可以用像「rgb(230,0,0)」這樣的值來設置這個值,並隨機生成紅綠藍色的整數值。

事情是這樣的:

r = Math.floor(Math.random() * 200); 
g = Math.floor(Math.random() * 200); 
b = Math.floor(Math.random() * 200); 
color = 'rgb(' + r + ', ' + g + ', ' + b + ')'; 

看到example jsfiddle here,使用隨機值和隨機顏色。 (運行幾次,以瞭解它如何顯示不同的數據集。)

或者你可以定義一個預定義顏色的數組,然後使用它。考慮一個超過50個項目的餅圖不是非常可靠的。所以50的默認列表可能就沒問題。

+0

嘿對不起,我跟着你的jsfiddle代碼,但它不工作。圖表沒有顯示任何內容,也沒有錯誤信息。你知道爲什麼這樣嗎? – hyperfkcb 2017-08-01 03:10:51

+0

嗨丹尼斯。我從一個不再存在的cdn調用chart.js。現在已經修復了。試試看,我已經更新了鏈接。 – rtome 2017-08-01 08:10:45

+0

非常感謝! – hyperfkcb 2017-08-01 08:15:38

1

我用15種不同的顏色創建了一個簡單的顏色系列。
他們不是隨機選擇的。相反,選擇顏色是爲了最大化近色的差異。

您仍然可以創建少於15個數據點的圖表,並且不會生成警告。

下面是代碼:

ctx = document.getElementById('myChart').getContext('2d'); 
chart = new Chart(ctx, { 
    type: 'pie', 
    data: { 
     datasets: [{ 
      label: 'Colors', 
      data: [9, 8, 7, 6, 5, 4, 3, 2, 1], 
      backgroundColor: ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"] 
     }], 
     labels: ['a','b','c','d','e','f','g','h','i'] 
    }, 
    options: { 
     responsive: true, 
     title:{ 
      display: true, 
      text: "Color test" 
     } 
    } 
}); 

這是HTML:

<canvas id="myChart" width="600" height="400"></canvas> 

enter image description here

如果你想用它玩,這裏是jsfiddle的代碼。

我希望這將有助於:)

1

首先,有很多色盲的人在那裏。以下是有關圖表和色盲一個很好的文章: Finding the Right Color Palettes for Data Visualizations

它使用chart.js之2.4.0

我是從這樣的梯度計算不同的顏色:

enter image description here

這給了一個很好的凝聚力的外觀。我從上面的鏈接借用了調色板。我只用甜甜圈,條形圖和折線圖進行了測試,但它應該很容易添加其他類型。您也可以輕鬆製作自己的漸變效果。

你可以找到一個jsfiddle here

HTML:

<div> 
    <button onclick="doughnut();">Doughnut</button> 
    <button onclick="lineBar('bar')">Bar</button> 
    <button onclick="lineBar('line')">Line</button> 
</div> 
<div> 
    <button onclick="chartColors('cool');">Cool</button> 
    <button onclick="chartColors('warm')">Warm</button> 
    <button onclick="chartColors('neon')">Neon</button> 
</div> 
<hr /> 
<canvas id="canvas"></canvas> 
<hr /> 
Palettes borrowed from:<br /> 
<a href="https://blog.graphiq.com/finding-the-right-color-palettes-for-data-visualizations-fcd4e707a283"> 
    Finding the Right Color Palettes for Data Visualizations 
</a> 

的Javascript:

var ctx = document.getElementById('canvas').getContext('2d'); 
var chart; 
var currentPalette = "cool"; 

function doughnut() { 
    if (chart) chart.destroy(); 
    chart = new Chart(ctx, { 
     type: 'doughnut', 
     data: { 
      labels: ["Bananas", "Street lights", "Emotions", "Colors", "Children", "Nodes"], 
      datasets: [{ 
       data: [1, 2, 6, 9, 1, 2], 
      }] 
     }, 
    }); 
    chartColors(); 
} 

function lineBar(type) { 
    if (chart) chart.destroy(); 
    chart = new Chart(ctx, { 
     type: type, 
     data: { 
      labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], 
      datasets: [{ 
       label: "Bananas", 
       data: [1, 2, 6, 9, 1, 2] 
      }, { 
       label: "Street lights", 
       data: [2, 6, 9, 1, 2, 7] 
      }, { 
       label: "Emotions", 
       data: [2, 4, 6, 8, 6, 4] 
      }, { 
       label: "Colors", 
       data: [3, 6, 3, 1, 3, 1] 
      }, { 
       label: "Children", 
       data: [4, 4, 4, 5, 5, 5] 
      }, { 
       label: "Nodes", 
       data: [5, 1, 2, 3, 4, 5] 
      }, ] 
     }, 
    }); 
    chartColors(); 
} 

function chartColors(palette) { 
    if (!palette) palette = currentPalette; 
    currentPalette = palette; 

    /*Gradients 
     The keys are percentage and the values are the color in a rgba format. 
     You can have as many "color stops" (%) as you like. 
     0% and 100% is not optional.*/ 
    var gradient; 
    switch (palette) { 
     case 'cool': 
      gradient = { 
       0: [255, 255, 255, 1], 
       20: [220, 237, 200, 1], 
       45: [66, 179, 213, 1], 
       65: [26, 39, 62, 1], 
       100: [0, 0, 0, 1] 
      }; 
      break; 
     case 'warm': 
      gradient = { 
       0: [255, 255, 255, 1], 
       20: [254, 235, 101, 1], 
       45: [228, 82, 27, 1], 
       65: [77, 52, 47, 1], 
       100: [0, 0, 0, 1] 
      }; 
      break; 
     case 'neon': 
      gradient = { 
       0: [255, 255, 255, 1], 
       20: [255, 236, 179, 1], 
       45: [232, 82, 133, 1], 
       65: [106, 27, 154, 1], 
       100: [0, 0, 0, 1] 
      }; 
      break; 
    } 

    //Get a sorted array of the gradient keys 
    var gradientKeys = Object.keys(gradient); 
    gradientKeys.sort(function(a, b) { 
     return +a - +b; 
    }); 

    //Find datasets and length 
    var chartType = chart.config.type; 
    switch (chartType) { 
     case "pie": 
     case "doughnut": 
      var datasets = chart.config.data.datasets[0]; 
      var setsCount = datasets.data.length; 
      break; 
     case "bar": 
     case "line": 
      var datasets = chart.config.data.datasets; 
      var setsCount = datasets.length; 
      break; 
    } 

    //Calculate colors 
    var chartColors = []; 
    for (i = 0; i < setsCount; i++) { 
     var gradientIndex = (i + 1) * (100/(setsCount + 1)); //Find where to get a color from the gradient 
     for (j = 0; j < gradientKeys.length; j++) { 
      var gradientKey = gradientKeys[j]; 
      if (gradientIndex === +gradientKey) { //Exact match with a gradient key - just get that color 
       chartColors[i] = 'rgba(' + gradient[gradientKey].toString() + ')'; 
       break; 
      } else if (gradientIndex < +gradientKey) { //It's somewhere between this gradient key and the previous 
       var prevKey = gradientKeys[j - 1]; 
       var gradientPartIndex = (gradientIndex - prevKey)/(gradientKey - prevKey); //Calculate where 
       var color = []; 
       for (k = 0; k < 4; k++) { //Loop through Red, Green, Blue and Alpha and calculate the correct color and opacity 
        color[k] = gradient[prevKey][k] - ((gradient[prevKey][k] - gradient[gradientKey][k]) * gradientPartIndex); 
        if (k < 3) color[k] = Math.round(color[k]); 
       } 
       chartColors[i] = 'rgba(' + color.toString() + ')'; 
       break; 
      } 
     } 
    } 

    //Copy colors to the chart 
    for (i = 0; i < setsCount; i++) { 
     switch (chartType) { 
      case "pie": 
      case "doughnut": 
       if (!datasets.backgroundColor) datasets.backgroundColor = []; 
       datasets.backgroundColor[i] = chartColors[i]; 
       if (!datasets.borderColor) datasets.borderColor = []; 
       datasets.borderColor[i] = "rgba(255,255,255,1)"; 
       break; 
      case "bar": 
       datasets[i].backgroundColor = chartColors[i]; 
       datasets[i].borderColor = "rgba(255,255,255,0)"; 
       break; 
      case "line": 
       datasets[i].borderColor = chartColors[i]; 
       datasets[i].backgroundColor = "rgba(255,255,255,0)"; 
       break; 
     } 
    } 

    //Update the chart to show the new colors 
    chart.update(); 
} 

doughnut(); 

這將給像這樣:

enter image description here