Bar Chart

Demo selecting bar color based on the bar’s y value.

Bar Chart - 图1

Randomize

options data setup

  1. function colorize(opaque) {
  2. return (ctx) => {
  3. const v = ctx.parsed.y;
  4. const c = v < -50 ? '#D60000'
  5. : v < 0 ? '#F46300'
  6. : v < 50 ? '#0358B6'
  7. : '#44DE28';
  8. return opaque ? c : Utils.transparentize(c, 1 - Math.abs(v / 150));
  9. };
  10. }
  11. const config = {
  12. type: 'bar',
  13. data: data,
  14. options: {
  15. plugins: {
  16. legend: false,
  17. },
  18. elements: {
  19. bar: {
  20. backgroundColor: colorize(false),
  21. borderColor: colorize(true),
  22. borderWidth: 2
  23. }
  24. }
  25. }
  26. };
  1. function generateData() {
  2. return Utils.numbers({
  3. count: DATA_COUNT,
  4. min: -100,
  5. max: 100
  6. });
  7. }
  8. const data = {
  9. labels: Utils.months({count: DATA_COUNT}),
  10. datasets: [{
  11. data: generateData(),
  12. }]
  13. };
  1. const DATA_COUNT = 16;
  2. Utils.srand(110);
  3. const actions = [
  4. {
  5. name: 'Randomize',
  6. handler(chart) {
  7. chart.data.datasets.forEach(dataset => {
  8. dataset.data = generateData();
  9. });
  10. chart.update();
  11. }
  12. },
  13. ];

Docs