我正在通过chartjs生成条形图。我有一个预定义的背景颜色数组,有 5 种颜色。我不知道我从 sql 查询中获得了多少数据。但我想使用预先确定的背景颜色。一旦我有超过 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)
}