Keeping scales in sync across multiple chart - Javascript Chart.js

Javascript examples for Chart.js:Chart Configuration

Description

Keeping scales in sync across multiple chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>chartjs-plugin-streaming #37</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> 
      <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming@1.5.0/dist/chartjs-plugin-streaming.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//  w  w  w.j  av a 2  s  .c  om
function rnorm () {
  return Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(2 * Math.PI * Math.random());
}
function updateScales() {
   var datasets = chart1.data.datasets.concat(chart2.data.datasets);
   chart1.options.scales.yAxes[0].ticks = chart2.options.scales.yAxes[0].ticks = {
     suggestedMin: Math.min(...datasets.map(function(dataset) {
        return Math.min(...dataset.data.map(function(value) {
             return value.y;
       }));
     })),
    suggestedMax: Math.max(...datasets.map(function(dataset) {
        return Math.max(...dataset.data.map(function(value) {
             return value.y;
       }));
        }))
  };
   chart1.update();
  chart2.update();
}
var ctx1 = document.getElementById('chart1').getContext('2d');
var chart1 = new Chart(ctx1, {
  type: 'line',
  data: {
     datasets: [{
       data: [],
    }]
  },
  options: {
    scales: {
       xAxes: [{
        type: 'realtime',
       }]
    },
    plugins: {
      streaming: {
        onRefresh: function(chart) {
          chart.data.datasets.forEach(function(dataset) {
            dataset.data.push({
              x: Date.now(),
              y: rnorm() * 100
            });
          });
          updateScales();
        }
      }
    }
  }
});
var ctx2 = document.getElementById('chart2').getContext('2d');
var chart2 = new Chart(ctx2, {
  type: 'line',
  data: {
     datasets: [{
       data: []
    }]
  },
  options: {
    scales: {
       xAxes: [{
        type: 'realtime',
       }]
    },
    plugins: {
      streaming: {
        onRefresh: function(chart) {
          chart.data.datasets.forEach(function(dataset) {
            dataset.data.push({
              x: Date.now(),
              y: rnorm() * 100
            });
          });
          updateScales();
        }
      }
    }
  }
});
    }

      </script> 
   </head> 
   <body> 
      <div style="width:50%;float:left">
         <canvas id="chart1"></canvas>
      </div> 
      <div style="width:50%;float:left">
         <canvas id="chart2"></canvas>
      </div>  
   </body>
</html>

Related Tutorials