简体   繁体   中英

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!

x 轴下方带有额外空白的折线图

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/

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.

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,
        },
      },
    ],
  },
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM