How to set default colour for bars in Chart.js(如何在 Chart.js 中为条形设置默认颜色)
问题描述
这似乎微不足道,但尽我所能尝试我似乎无法找到如何为 chart.js 中的条形设置默认颜色.
This seems stupidly trivial but try as I might I cannot seem to find how to set a default colour for bars in chart.js.
我的图表正在从 ajax 请求中获取数据,并且图表呈现得很好.但是,无论是更新 Chart.defaults.global.defaultColor 还是将 defaultColor 作为选项添加到数据集都没有任何效果.
My charts is taking its data from an ajax request and the chart is rendering just fine. However neither updating Chart.defaults.global.defaultColor nor adding defaultColor to the dataset as an option has any effect.
我非常感谢任何人在这里指出我正确的方向.
I would very much appreciate anyone pointing me in the right direction here.
$.ajax({
type: 'GET',
async: true,
url: "{{route('stats.monthlyData')}}",
dataType: 'json',
success: function (response) {
var labels = [];
var data = [];
$.each(response, function () {
labels.push(this.month_name);
data.push(this.record_count);
});
drawChart('# of Records', labels, data);
}
});
function drawChart(label, labels, data){
var ctx = document.getElementById("chart");
//Chart.defaults.global.defaultColor = "#3498db"; Tried this but does not work
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: label,
data: data,
//defaultColor: ['#3498db'], Tried this but does not work
backgroundColor: ['#3498db'], //Only the first bar gets set
borderColor: [],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
谢谢.
更新
如果它对任何人都有帮助,问题是我将 backgroundColor 属性设置为只有一个条目的数组.如果你想为所有列默认它,那么它应该只设置为一个字符串.感谢 @mp77 让我注意到这个问题.
In case it helps anyone, the issue was that I was setting the backgroundColor property to an array with only a single entry. If you want to default it for all columns then it should only be set to a string. Credit to @mp77 for leading me to notice this issue.
推荐答案
您需要像这样在 datasets
数组中使用 fillColor
属性 -(而不是 borderColor
,尝试 strokeColor
如下所示)
You need to use fillColor
property in your datasets
array like this -
(and instead of borderColor
, try strokeColor
like below)
datasets: [{
label: label,
data: data,
fillColor: "rgba(14,72,100,1)", //version >2 useus background color
strokeColor: "brown",
borderWidth: 1
}]
可以从 chartjs 的一个演示中看到一个完整的工作示例这里
A full working example can be seen from one of the demos of chartjs here
这篇关于如何在 Chart.js 中为条形设置默认颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Chart.js 中为条形设置默认颜色
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01