[Chartjs]-Adding color dynamically to Chart.js

1πŸ‘

βœ…

In the following code snippet, I work with simple color definitions for illustrating how it can be done. Simply replace the colors array with your own colors and it should work as expected.

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

const colors = ['red', 'orange', 'yellow', 'green', 'blue']; 
const labels = Array.from(new Set(response.map(c => c.mmyy))).sort();
const promocodes = Array.from(new Set(response.map(c => c.promocode))).sort();
let i = 0; 
const datasets = promocodes.map(pc => ({
  label: pc,
  data: [],
  backgroundColor: colors[i++]
}));
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: {
          callback: (value, index, values) => '$' + value
        }
      }]
    },
    tooltips: {
      callbacks: {
        label: (tooltipItems, data) => "$" + 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>

0πŸ‘

I just modified the code. You have to set up the backgroundcolor for custom bar colors.

//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

0πŸ‘

add this property inside our datasets => backgroundColor: [β€˜#3a95cd’,’#4e5ea2β€²]

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: [],
  backgroundColor: ['#3a95cd','#4e5ea2'] //  ['#3a95cd','#4e5ea2']
}));
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>

Leave a comment