Chart.js - Increase spacing between legend and chart

人盡茶涼 提交于 2019-11-27 21:16:02

Unfortunately, since there is no config option to handle this the only way you can achieve the desired result is to extend Chart.Legend and implement the afterFit() callback.

Here is a quick codepen showing how to do just that. To change the spacing, just change the value in line 9 (currently set to 50). Also, this of course only works with the legend at the top. Hopefully, the example is clear enough for you to modify in case you want to move your legend elsewhere.

If you want do increase spacing in all charts you can put this code before creating :

Chart.Legend.prototype.afterFit = function() {
    this.height = this.height + 50;
};

Of course, I don't try but i think you can change it (or copy the original Chart object before, to keep the original padding).

Bye,

If you want to apply padding below legend for some charts only in your app:

ChartJS >= 2.1.0

Chart.plugins.register({
  id: 'paddingBelowLegends',
  beforeInit: function(chart, options) {
    chart.legend.afterFit = function() {
      this.height = this.height + 50;
    };
  }
});

// ----------------------------------
// disable the plugin only for charts
// where you DO NOT WANT the padding
// ----------------------------------

// for raw ChartJS use:
var chart = new Chart(ctx, {
  config: {
    plugins: {
      paddingBelowLegends: false
    }
  }
});

// for angular-chartjs:
$scope.myChart.options.plugins = { paddingBelowLegends: false }
// then in template:
// <canvas class="chart ..." chart-options="myChart.options" ... />

ChartJS >= 2.5.0

Specific plugins for each chart are supported, it should be possible to do:

var chart = new Chart(ctx, {
  plugins: [{
    beforeInit: function(chart, options) {
      chart.legend.afterFit = function() {
        this.height = this.height + 50;
      };
    }
  }]
});

See ChartJS documentation + inspired by this other answer

sahil ralkar

This helped me after 2 days of research.

Chart.Legend.prototype.afterFit = function() {
    this.height = this.height + 50;
};

update this in module.ts file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!