Javascript – ChartJS line chart drag and zoom

ChartJS line chart drag and zoom… here is a solution to the problem.

ChartJS line chart drag and zoom

Is it possible to add drag and zoom functionality on ChartJS? I want to do something like here

Here’s how I drew a line chart:

<canvas class="square_margin_less" id="myChart" width="100" height="30" > </canvas>
<script>
new Chart(document.getElementById("myChart").getContext('2d'),
{
    type: 'line',
    data: {
        labels: {{ data.labels|safe }},
        datasets:
        [{
            label: 'x',
            data: {{ data.x }},
            borderColor: 'rgba(233,105,118,1)',
        },
        {
            label: 'y',
            data: {{ data.y }},
            borderColor: 'rgba(96,143,239,1)'
        },
        {
            label: 'z',
            data: {{ data.z }},
            borderColor: 'rgba(144,247,136,1)'
        }]
    },
});
</script>

Are there any personalized approaches?

Solution

I

didn’t find a simple example of Chart.js’s Drag & Zoom feature and the Pan & Zoom version, so I decided to implement the demo version myself.

The list of external scripts is very important: hammer-js, then Chart.bundle.js and chartjs-plugin-zoom.js

 const config = {
  type: 'line',
  data: {
    labels: [new Date('2019-08-20'), new Date('2019-08-25'), new Date('2019-08-30')],
    datasets: [{
      label: 'Line',
      data: [2, 5, 3],
      borderColor: '#D4213D',
      fill: false,
    }, ],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
      }, ],
    },
    pan: {
      enabled: true,
      mode: 'xy',
    },
    zoom: {
      enabled: true,
      mode: 'xy', // or 'x' for "drag" version
    },
  },
};

window.onload = function() {
  new Chart(document.getElementById('chart'), config);
}; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/0.6.6/chartjs-plugin-zoom.js"></script>
<html>
<body>
  <div style="width:380px; ">
    <canvas id="chart"></canvas>
  </div>
</body>
</html>

If anyone is interested in other libraries, I found an interesting solution on the Vicotry website with the “brush and zoom” feature of line charts: https://formidable.com/open-source/victory/guides/brush-and-zoom/ .

EDIT: In the “drag” version, you must use Zoom:

drag: {
   borderColor: 'hsl(35, 100%, 60%)',
   borderWidth: '3',
   backgroundColor: 'hsl(35, 100%, 60%)',
},

Related Problems and Solutions