bar-stacked.html 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>Stacked Bar Chart</title>
  5. <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  6. <script src="../dist/Chart.bundle.js"></script>
  7. <style>
  8. canvas {
  9. -moz-user-select: none;
  10. -webkit-user-select: none;
  11. -ms-user-select: none;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div style="width: 75%">
  17. <canvas id="canvas"></canvas>
  18. </div>
  19. <button id="randomizeData">Randomize Data</button>
  20. <script>
  21. var randomScalingFactor = function() {
  22. return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
  23. };
  24. var randomColorFactor = function() {
  25. return Math.round(Math.random() * 255);
  26. };
  27. var barChartData = {
  28. labels: ["January", "February", "March", "April", "May", "June", "July"],
  29. datasets: [{
  30. label: 'Dataset 1',
  31. backgroundColor: "rgba(220,220,220,0.5)",
  32. data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
  33. }, {
  34. label: 'Dataset 2',
  35. backgroundColor: "rgba(151,187,205,0.5)",
  36. data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
  37. }, {
  38. label: 'Dataset 3',
  39. backgroundColor: "rgba(151,187,205,0.5)",
  40. data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
  41. }]
  42. };
  43. window.onload = function() {
  44. var ctx = document.getElementById("canvas").getContext("2d");
  45. window.myBar = new Chart(ctx, {
  46. type: 'bar',
  47. data: barChartData,
  48. options: {
  49. title:{
  50. display:true,
  51. text:"Chart.js Bar Chart - Stacked"
  52. },
  53. tooltips: {
  54. mode: 'label'
  55. },
  56. responsive: true,
  57. scales: {
  58. xAxes: [{
  59. stacked: true,
  60. }],
  61. yAxes: [{
  62. stacked: true
  63. }]
  64. }
  65. }
  66. });
  67. };
  68. $('#randomizeData').click(function() {
  69. $.each(barChartData.datasets, function(i, dataset) {
  70. dataset.backgroundColor = 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)';
  71. dataset.data = [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()];
  72. });
  73. window.myBar.update();
  74. });
  75. </script>
  76. </body>
  77. </html>