How to set default colour for bars in Chart.js

半腔热情 提交于 2020-01-13 09:34:10

问题


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.

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

}

Thanks.

UPDATE

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.


回答1:


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
}]

A full working example can be seen from one of the demos of chartjs here



来源:https://stackoverflow.com/questions/43117395/how-to-set-default-colour-for-bars-in-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!