hide values past the x-axis in line chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

hide values past the x-axis in line chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/* w w w  .  j  a  va 2  s .  co m*/
var ctx = document.getElementById("canvas").getContext("2d");
var cleanOutPlugin = {
   beforeInit: function(chart) {
       // Replace `ticks.min` by `time.min` if time-type chart
        var min = chart.config.options.scales.xAxes[0].ticks.min;
        // Same here with `ticks.max`
        var max = chart.config.options.scales.xAxes[0].ticks.max;
        var ticks = chart.config.data.labels;
        var idxMin = ticks.indexOf(min);
        var idxMax = ticks.indexOf(max);
        if (idxMin == -1 || idxMax == -1)
           return;
        var data = chart.config.data.datasets[0].data;
        data.splice(idxMax + 1, ticks.length - idxMax);
        data.splice(0, idxMin);
        ticks.splice(idxMax + 1, ticks.length - idxMax);
        ticks.splice(0, idxMin);
    }
};
Chart.pluginService.register(cleanOutPlugin);
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [1, 2, 3, 4, 5, 6, 7],
        datasets: [{
            label: "My Dataset",
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: [65, 59, 80, 81, 56, 55, 40],
            spanGaps: false,
        }]
    },
    options: {
        scales: {
            xAxes: [{
               ticks: {
                    min: 2,
                    max: 6
                }
            }],
        }
    }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" height="200"></canvas>  
   </body>
</html>

Related Tutorials