javascriptc3.js

How to implement C3 chart zoom functionality on a button click


I am new to C3 chart. I found the zoom functionality in the documentation for C3 . It will work for the mouse wheel scroll. But what I want is to implement the zoomin and zoomout in two seperate buttons. Can anyone direct me to the right track.

Thanks in advance.


Solution

  • Here below is an example of zoom in/out managed with buttons. However unlike mouse wheel you have to decide which starting point to use.

    var chart = c3.generate({
        data: {
            columns: [
                ['sample', 30, 200, 100, 400, 150, 250, 150, 200, 170, 240, 350, 150, 100, 400, 150, 250, 150, 200, 170, 240, 100, 150, 250, 150, 200, 170, 240, 30, 200, 100, 400, 150, 250, 150, 200, 170, 240, 350, 150, 100, 400, 350, 220, 250, 300, 270, 140, 150, 90, 150, 50, 120, 70, 40]
            ]
        },
        zoom: {
            enabled: true,
            rescale: true,
            onzoom: function (domain) { 
            	console.log("zoom", domain);
            }
        }
    });
    
    var zoom = 1;
    var zoom_factor = 1.1;
    var min = 0;
    var max = chart.data()[0].values.length;
    
    $("#zoom-in").click(function() {
    	if (zoom<5) zoom *= zoom_factor;
      console.log("zoom-in", min, max, zoom);
    	chart.zoom([min, max/zoom]);
    });
    
    $("#zoom-out").click(function() {
    	if (zoom>1) zoom /= zoom_factor;
      console.log("zoom-out", min, max, zoom);
    	chart.zoom([min, max/zoom]);
    });
    
    $("#zoom-reset").click(function() {
    	zoom = 1;
      console.log("zoom-reset", min, max, zoom);
    	chart.zoom([min, max/zoom]);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
    <link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet"/>
    <script src="https://rawgit.com/masayuki0812/c3/master/c3.js"></script>
    
    <button id="zoom-in">zoom-in</button>
    <button id="zoom-out">zoom-out</button>
    <button id="zoom-reset">zoom-reset</button>
    <div id="chart"></div>