Chartjs-Multiple Graphs on one page

0👍

One way I could think of is creating a function, if all of your charts are similar and only few parameters change, for example in the following example I’ve considered chartId, labels, dataset and title to be varying. You can also aim to write function that creates datasets given certain parameters:

var randomScalingFactor = function() {
  return Math.round(Math.random() * 100);
};
window.chartColors = {
  red: 'rgb(255, 99, 132)',
  orange: 'rgb(255, 159, 64)',
  yellow: 'rgb(255, 205, 86)',
  green: 'rgb(75, 192, 192)',
  blue: 'rgb(54, 162, 235)',
  purple: 'rgb(153, 102, 255)',
  grey: 'rgb(201, 203, 207)'
};
var color = Chart.helpers.color;
var labels = [
  ['Shots on', ' Target'],
  ['Shots Off', 'Target'], 'Corners', 'possession (out of 10)'
];
var datasets = [{
  label: 'Home team',
  backgroundColor: color(window.chartColors.red).alpha(0.2).rgbString(),
  borderColor: window.chartColors.red,
  pointBackgroundColor: window.chartColors.red,
  data: ['5', '7', '4', '6', '2']
}, {
  label: 'Away Team',
  backgroundColor: color(window.chartColors.blue).alpha(0.2).rgbString(),
  borderColor: window.chartColors.blue,
  pointBackgroundColor: window.chartColors.blue,
  data: ['2', '1', '3', '5', '0']
}];

window.onload = function() {
  window.myRadar = createChart('canvas', labels, datasets, 'In Play Stats');
};

function createChart(chartId, labels, dataset, title) {
  return new Chart(document.getElementById(chartId), {
    type: 'radar',
    data: {
      labels: labels,
      datasets: dataset
    },
    options: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: title
      },
      scale: {
        ticks: {
          beginAtZero: true
        }
      }
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="width:40%; min-width: 700px;">
  <canvas id="canvas" style="width: 700px;"></canvas>
</div>

Leave a comment