Chart.js - Increase Spacing Between Legend And Chart


Answer :

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


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.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?