Stacked bar/line

Stacked bar/line - 图1

RandomizeAdd DatasetAdd DataRemove DatasetRemove Data

config setup actions

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

Docs