Lechucico
Lechucico

Reputation: 2112

ChartJS line chart drag and zoom

Is it possible to add drag and zoom on ChartJS? I would like to do something similar like here.

Here is how I draw my 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>

There is some way of personalizing this?

Upvotes: 3

Views: 13391

Answers (1)

plkpiotr
plkpiotr

Reputation: 374

I didn't find "drag and zoom" functionality for Chart.js as well as simple example with "pan and zoom" version so I've decided to implement demo version own my own.

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 someone is interesting in other libraries, I found one interesting solution on Vicotry website with "brush and zoom" functionality for line charts: https://formidable.com/open-source/victory/guides/brush-and-zoom/.

EDIT: In the "drag" version you will have to use for zoom:

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

Upvotes: 3

Related Questions