Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove extra whitespace from the bottom of a line chart in chart.js?

As you can see below with the canvas element highlighted, there is considerable whitespace below the x axis label. If I resize the canvas, the whitespace stays proportional to the height of it. Are there any settings that control this whitespace? I've ruled out padding and do not see any settings for margins.

Thanks!

Line chart with extra whitespace below x axis

Here is the JavaScript that renders the chart:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  options: {
    legend: {
      display: false
    },
    elements: {
      point: {
        radius: 0
      }
    },
    scales: {
      xAxes: [{
        gridLines: {
          display: false,
          drawBorder: true
        },
        ticks: {
          autoSkip: true,
          maxTicksLimit: 1
        }
      }],
      yAxes: [{
        gridLines: {
          display: true,
          drawBorder: false
        },
        ticks: {
          callback: function(value, index, values) {
            return '$' + addCommas(value);
          }
        }
      }]
    },
    layout: {
      padding: 5
    }
  },
  type: 'line',
  data: {
    labels: labels,
    datasets: [
      { 
        data: values,
        fill: false,
        borderColor: "blue"
      }
    ]
  }
});

And the complete jsfiddle: https://jsfiddle.net/rsn288fh/2/

like image 669
cdlm Avatar asked Nov 28 '17 11:11

cdlm


2 Answers

I know you said you ruled out padding, but this is the only option I can see working:

options: {
    layout: {
        padding: {
            bottom: -20
        }
    }
}

Obviously you can play with the -20 to what works for you.

Here is the reference for padding for chartjs, if you wanted to see more

EDIT:

I've updated your jsfiddle, with a colored div below the chart. As you resize it seems to stay at the same spot below the chart.

like image 148
tyelford Avatar answered Sep 20 '22 13:09

tyelford


Changing the tickMarkLength to 0 results in no padding on the left or bottom of the chart (or wherever your axis happens to be).

https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration

tickMarkLength

Length in pixels that the grid lines will draw into the axis area.

const options = {
  scales: {
    xAxes: [
      {
        ticks: {
          display: false,
        },
        gridLines: {
          display: false,
          tickMarkLength: 0,
        },
      },
    ],
    yAxes: [
      {
        ticks: {
          display: false,
        },
        gridLines: {
          display: false,
          tickMarkLength: 0,
        },
      },
    ],
  },
};
like image 43
Ben Swinburne Avatar answered Sep 16 '22 13:09

Ben Swinburne