Vertical Bar Chart

Vertical Bar Chart - 图1

Randomize Add Dataset Add Data Remove Dataset Remove Data

config setup actions

  1. const config = {
  2. type: 'bar',
  3. data: data,
  4. options: {
  5. responsive: true,
  6. plugins: {
  7. legend: {
  8. position: 'top',
  9. },
  10. title: {
  11. display: true,
  12. text: 'Chart.js Bar Chart'
  13. }
  14. }
  15. },
  16. };
  1. const DATA_COUNT = 7;
  2. const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100};
  3. const labels = Utils.months({count: 7});
  4. const data = {
  5. labels: labels,
  6. datasets: [
  7. {
  8. label: 'Dataset 1',
  9. data: Utils.numbers(NUMBER_CFG),
  10. borderColor: Utils.CHART_COLORS.red,
  11. backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5),
  12. },
  13. {
  14. label: 'Dataset 2',
  15. data: Utils.numbers(NUMBER_CFG),
  16. borderColor: Utils.CHART_COLORS.blue,
  17. backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5),
  18. }
  19. ]
  20. };
  1. const actions = [
  2. {
  3. name: 'Randomize',
  4. handler(chart) {
  5. chart.data.datasets.forEach(dataset => {
  6. dataset.data = Utils.numbers({count: chart.data.labels.length, min: -100, max: 100});
  7. });
  8. chart.update();
  9. }
  10. },
  11. {
  12. name: 'Add Dataset',
  13. handler(chart) {
  14. const data = chart.data;
  15. const dsColor = Utils.namedColor(chart.data.datasets.length);
  16. const newDataset = {
  17. label: 'Dataset ' + (data.datasets.length + 1),
  18. backgroundColor: Utils.transparentize(dsColor, 0.5),
  19. borderColor: dsColor,
  20. borderWidth: 1,
  21. data: Utils.numbers({count: data.labels.length, min: -100, max: 100}),
  22. };
  23. chart.data.datasets.push(newDataset);
  24. chart.update();
  25. }
  26. },
  27. {
  28. name: 'Add Data',
  29. handler(chart) {
  30. const data = chart.data;
  31. if (data.datasets.length > 0) {
  32. data.labels = Utils.months({count: data.labels.length + 1});
  33. for (var index = 0; index < data.datasets.length; ++index) {
  34. data.datasets[index].data.push(Utils.rand(-100, 100));
  35. }
  36. chart.update();
  37. }
  38. }
  39. },
  40. {
  41. name: 'Remove Dataset',
  42. handler(chart) {
  43. chart.data.datasets.pop();
  44. chart.update();
  45. }
  46. },
  47. {
  48. name: 'Remove Data',
  49. handler(chart) {
  50. chart.data.labels.splice(-1, 1); // remove the label first
  51. chart.data.datasets.forEach(dataset => {
  52. dataset.data.pop();
  53. });
  54. chart.update();
  55. }
  56. }
  57. ];