向Chart.js动态添加颜色

问题描述 投票:0回答:2

我有一个Chart.js项目,下面的代码对此做了最好的解释。

const response = [ 
   { 
      "mmyy":"2019-12",
      "promocode":"promo1",
      "amount":"2776"
   },
   { 
      "mmyy":"2020-01",
      "promocode":"promo1",
      "amount":"1245"
   },
   { 
      "mmyy":"2020-01",
      "promocode":"promo2",
      "amount":"179"
   }
];

          var chartColors = window.chartColors;
          var color = Chart.helpers.color;

          var colors = [color(chartColors.red).alpha(0.5).rgbString(),
            color(chartColors.orange).alpha(0.5).rgbString(),
            color(chartColors.yellow).alpha(0.5).rgbString(),
            color(chartColors.green).alpha(0.5).rgbString(),
            color(chartColors.blue).alpha(0.5).rgbString()]; 

          var bgColors = [];


const labels = Array.from(new Set(response.map(c => c.mmyy))).sort();
const promocodes = Array.from(new Set(response.map(c => c.promocode))).sort();
const datasets = promocodes.map(pc => ({ label: pc, data: [] }));
labels.forEach(l => {    

    for (let pc of promocodes) {
      let city = response.find(c => c.mmyy == l && c.promocode == pc);
        datasets.find(ds => ds.label == pc).data.push(city ? Number(city.amount) : 0);
    }
});

var ctx = document.getElementById('promorChart').getContext('2d');

var chartColors = window.chartColors;
var color = Chart.helpers.color;

var promorChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: datasets
    },

    options: {
        scales: {
            xAxes: [{
              stacked: false
            }],
            yAxes: [{
              stacked: false,
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                        return '$' + value;
                    }
                }
            }]
        },
        tooltips: {
            callbacks: {
                label: function(tooltipItems, data) {
                    return "$" + tooltipItems.yLabel.toString();
                }
            }
        },
        responsive: true,
        elements: {
        }
    }
});
<canvas id="promorChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://www.chartjs.org/samples/latest/utils.js"></script>

它很好用,但是如您所见,它需要一些颜色,所以我正在尝试使用此代码添加一些颜色:

    const labels = Array.from(new Set(response.map(c => c.mmyy))).sort();
const promocodes = Array.from(new Set(response.map(c => c.promocode))).sort();
const datasets = promocodes.map(pc => ({ label: pc, data: [], backgroundColor: bgColors }));
labels.forEach(l => {    

    for (var i = 0; i < labels.count.length; i++) {
            let bgColors = (colors[i % colors.length]);  
    };

    for (let pc of promocodes) {
      let city = response.find(c => c.mmyy == l && c.promocode == pc);
        datasets.find(ds => ds.label == pc).data.push(city ? Number(city.amount) : 0);
    }
});

但是那不起作用。我收到错误TypeError: undefined is not an object (evaluating 'labels.count.length')有人可以告诉我如何为每个标签正确添加颜色,从而正确地形成颜色数组吗?谢谢。

javascript chart.js
2个回答
0
投票
在以下代码段中,使用颜色方案chartjs-plugin-colorschemes使用brewer.DarkTwo3自动定义背景色。您可以用任何其他选择替换当前的配色方案(请参见https://nagix.github.io/chartjs-plugin-colorschemes/colorchart.html)。

const response = [{ "mmyy": "2019-12", "promocode": "promo1", "amount": "2776" }, { "mmyy": "2020-01", "promocode": "promo1", "amount": "1245" }, { "mmyy": "2020-01", "promocode": "promo2", "amount": "179" } ]; const labels = Array.from(new Set(response.map(c => c.mmyy))).sort(); const promocodes = Array.from(new Set(response.map(c => c.promocode))).sort(); const datasets = promocodes.map(pc => ({ label: pc, data: [] })); labels.forEach(l => { for (let pc of promocodes) { let city = response.find(c => c.mmyy == l && c.promocode == pc); datasets.find(ds => ds.label == pc).data.push(city ? Number(city.amount) : 0); } }); var ctx = document.getElementById('promorChart').getContext('2d'); var chartColors = window.chartColors; var color = Chart.helpers.color; var promorChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: datasets }, options: { plugins: { colorschemes: { scheme: 'brewer.DarkTwo3' } }, scales: { xAxes: [{ stacked: false }], yAxes: [{ stacked: false, ticks: { callback: function(value, index, values) { return '$' + value; } } }] }, tooltips: { callbacks: { label: function(tooltipItems, data) { return "$" + tooltipItems.yLabel.toString(); } } }, responsive: true, elements: {} } });
<canvas id="promorChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-colorschemes"></script>

0
投票
我刚刚修改了代码。您必须为自定义条形颜色设置backgroundcolor。

const response = [ { "mmyy":"2019-12", "promocode":"promo1", "amount":"2776" }, { "mmyy":"2020-01", "promocode":"promo1", "amount":"1245" }, { "mmyy":"2020-01", "promocode":"promo2", "amount":"179" } ]; //added for colors function colorsFunction() { return ['#3e95cd','#8e5ea2']; } const labels = Array.from(new Set(response.map(c => c.mmyy))).sort(); const promocodes = Array.from(new Set(response.map(c => c.promocode))).sort(); const datasets = promocodes.map(pc => ({ label: pc, data: [],backgroundColor: colorsFunction() })); //Modified here labels.forEach(l => { for (let pc of promocodes) { let city = response.find(c => c.mmyy == l && c.promocode == pc); datasets.find(ds => ds.label == pc).data.push(city ? Number(city.amount) : 0); } }); var ctx = document.getElementById('promorChart').getContext('2d'); var promorChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: datasets }, options: { scales: { xAxes: [{ stacked: false }], yAxes: [{ stacked: false, ticks: { // Include a dollar sign in the ticks beginAtZero: true, callback: function(value, index, values) { return '$' + value; } } }] }, tooltips: { callbacks: { label: function(tooltipItems, data) { return "$" + tooltipItems.yLabel.toString(); } } }, responsive: true, elements: { } } });

© www.soinside.com 2019 - 2024. All rights reserved.