我正在通过chartjs生成条形图。我有5种颜色的预定义backgroundcolor数组。我不知道我从sql查询中获得了多少数据。但我想使用预先指定的backgroundcolor。一旦我有5条以上的数据记录,其他栏将无法正确显示。正确显示第1至5条。 5号之后的所有条形都显示为灰色/黑色。我怎么能知道,条形#6获得#1的背景色,而#7获得#2的背景色,依此类推...?
var chartdata = {
labels: name,
datasets: [{
label: 'My Label here',
//backgroundColor: ['#3066be', '#2de1c2','#87bcde','#907ad6','#845a6d'],
backgroundColor:[
"rgba(255, 159, 64, 0.2)", //orange
"rgba(255, 205, 86, 0.2)", //yellow
"rgba(75, 192, 192, 0.2)", // green
"rgba(54, 162, 235, 0.2)", // blue
"rgba(153, 102, 255, 0.2)"], //purple
borderColor:[
"rgb(255, 159, 64)", //orange
"rgb(255, 205, 86)", //yellow
"rgb(75, 192, 192)", //green
"rgb(54, 162, 235)", //blue
"rgb(153, 102, 255)"], //purple
borderWidth: 2,
hoverBackgroundColor: [
"rgba(255, 159, 64, 0.4)", //orange
"rgba(255, 205, 86, 0.4)", //yellow
"rgba(75, 192, 192, 0.4)", // green
"rgba(54, 162, 235, 0.4)", // blue
"rgba(153, 102, 255, 0.4)"], //purple
data: marks
}]};
首先,在图表配置之外定义data
和color
数组。然后,您可以使用以下函数生成具有重复颜色的新数组:
function repeatColors(data, colors) {
var result = [];
for (var i = 0; i < data.length; i++) {
result.push(colors[i % colors.length]);
}
return result;
}
请看下面的代码示例:
var labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];
var data = [8, 7, 5, 4, 3, 6, 2, 5, 7, 3, 8, 4, 6];
var bgColors = [
"rgba(255, 159, 64, 0.2)", //orange
"rgba(255, 205, 86, 0.2)", //yellow
"rgba(75, 192, 192, 0.2)", // green
"rgba(54, 162, 235, 0.2)", // blue
"rgba(153, 102, 255, 0.2)" //purple
];
var borderColors = [
"rgb(255, 159, 64)", //orange
"rgb(255, 205, 86)", //yellow
"rgb(75, 192, 192)", //green
"rgb(54, 162, 235)", //blue
"rgb(153, 102, 255)" //purple
];
var hoverBgColors = [
"rgba(255, 159, 64, 0.4)", //orange
"rgba(255, 205, 86, 0.4)", //yellow
"rgba(75, 192, 192, 0.4)", // green
"rgba(54, 162, 235, 0.4)", // blue
"rgba(153, 102, 255, 0.4)" //purple
];
function repeatColors(data, colors) {
var result = [];
for (var i = 0; i < data.length; i++) {
result.push(colors[i % colors.length]);
}
return result;
}
new Chart(document.getElementById('canvas'), {
type: 'bar',
data: {
labels: labels,
datasets: [{
data: data,
backgroundColor: repeatColors(data, bgColors),
borderColor: repeatColors(data, borderColors),
borderWidth: 2,
hoverBackgroundColor: repeatColors(data, hoverBgColors)
}]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" height="80"></canvas>
我错误地使用了ajax请求。因此,我无法确定来自请求的数据长度。我这样解决了:
$.post("some_file.php", '', function(data) {
iDependOnMyParameter(data);
});
function iDependOnMyParameter(param) {
// You should do your work here that depends on the result of the request!
alert(param)
}