generate-chart.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. function randomColor() {
  2. return {
  3. r: Math.floor(Math.random() * 256),
  4. g: Math.floor(Math.random() * 256),
  5. b: Math.floor(Math.random() * 256)
  6. };
  7. }
  8. function generateBarChart(elt, title, colname, data) {
  9. let dataset = []
  10. data.forEach(element => {
  11. let color = element.color ? element.color : randomColor();
  12. let chartData = {
  13. label: element.title,
  14. backgroundColor: `rgba(${color.r}, ${color.g}, ${color.b}, 0.2)`,
  15. borderColor: `rgb(${color.r}, ${color.g}, ${color.b})`,
  16. borderWidth: 1,
  17. data: element.value
  18. };
  19. if(element.line !== undefined && element.line) {
  20. chartData['type'] = 'line';
  21. chartData['fill'] = false;
  22. }
  23. dataset.push(chartData);
  24. });
  25. ctx = elt.getContext('2d');
  26. return new Chart(ctx, {
  27. type: 'bar',
  28. data: {
  29. labels: colname,
  30. datasets: dataset
  31. },
  32. options: {
  33. responsive: true,
  34. legend: {
  35. position: 'top',
  36. },
  37. title: {
  38. display: true,
  39. text: title
  40. },
  41. scales: {
  42. yAxes: [{
  43. ticks: {
  44. beginAtZero: true
  45. }
  46. }]
  47. }
  48. }
  49. });
  50. }