Search code examples
javascriptgraphchartschart.jschart.js2

Chart.js Clipping on Top of Line Graph


I have a chart in Chart.js to show the outside temperature for the past 2 hours, but whenever the range is really big, the chart will get cut off and clip at the top and I've tried many methods to attempt to fix it but it just won't work. Is there an option that I can add to help it scale accordingly to the maximum value? Any help would be appreciated. Thanks.

Image: https://i.sstatic.net/P2fJc.jpg

JavaScript (Snippet):

var chart = new Chart(ctx, {
    type: 'line',

    data: {
        labels: labels,
        datasets: [{
            label: 'Outdoor Temperature',
            backgroundColor: graphBgColor,
            borderColor: graphBorderColor,
            data: tempdata,
            }]
    },


    options: {
        scaleLabel: " <%= Number(value / 1000) + ' MB'%>"
    }
});

Solution

  • To resolve this, you need to set a maximum value for y-axis ticks, based on your tempdata array, like so :

    options: {
       scales: {
          yAxes: [{
             ticks: {
                max: Math.max.apply(null, tempdata) + 1, //max value + 1
             }
          }]
       },
       ...
    }
    

    ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

    var labels = ['Jan', 'Feb', 'Mar', 'Apr'];
    var tempdata = [2, 4, 1, 3];
    var graphBgColor = 'rgba(0, 119, 204, 0.1)';
    var graphBorderColor = 'rgba(0, 119, 204, 0.5)';
    
    var chart = new Chart(ctx, {
       type: 'line',
       data: {
          labels: labels,
          datasets: [{
             label: 'Outdoor Temperature',
             backgroundColor: graphBgColor,
             borderColor: graphBorderColor,
             data: tempdata,
          }]
       },
       options: {
          scales: {
             yAxes: [{
                ticks: {
                   max: Math.max.apply(null, tempdata) + 1, //max value + 1
                }
             }]
          }
       }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
    <canvas id="ctx"></canvas>