Chart.js - Increase the distance between the legend and the chart

I have a histogram in which I drew 3 vertical lines, each with its own label at the top. I would like these labels to be above the top of the y axis (above the 30% line in the example), but below the legend. I cannot figure out how to increase the space between the upper legend and the diagram so that my vertical line marks (15, 24 and 33) are separated from the diagram itself, but below the legend. Any ideas?

Chart example

+15
source share
4 answers

Unfortunately, since there is no configuration option for this, the only way to achieve the desired result is to extend Chart.Legend and implement the afterFit() .

Here is a quick codepen showing how to do this. To change the interval, simply change the value in line 9 (currently set to 50). Moreover, this, of course, only works with the legend above. Hopefully this example is clear enough so that you can change it if you want to move your legend elsewhere.

+12
source

If you want to increase the intervals in all diagrams, you can put this code before creating:

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

Of course, I am not trying, but I think you can change it (or copy the original Chart object earlier to save the original addition).

Bye,

+10
source

If you want to indent under the legend for some diagrams only in your application:

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

For each chart, certain plugins are supported, this 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

+4
source

It helped me after 2 days of research.

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

update this in module.ts file

0
source

Source: https://habr.com/ru/post/1015451/


All Articles