I'm working with doughnut graphs using ChartJS and I'm having a bad time trying to create some kind of space between the graph and the legend.
That's my legend config:
plugins: {
legend: {
display: true,
align: 'start',
position: 'bottom',
}
}
And that's the plugin I wrote to add more height to the legend:
const LegendMargin = {
id: 'LegendMargin',
beforeInit(chart, legend, options) {
const fitValue = chart.legend.fit;
chart.legend.fit = function fit() {
fitValue.bind(chart.legend)();
this.height += 40;
}
}
}
This plugin increased the height of the legend below the graph, but the text is still aligned to the top of the box, which doesn't fix the problem.
Can I somehow align the text to the bottom of the box or create some sort of margin/padding between the legend and the graph?
Thank you so much
It seems like the legend top position can be controlled using the legend.top property. But this property is managed by chart.js itself. So if you change it, is gonna be overwritten. So one hacky way to get around it is to use Object.defineProperty to intercept calls to legend.top like that:
const LegendMarginPlugin = {
id: 'LegendMarginPlugin',
beforeInit(chart, legend, options) {
const fitValue = chart.legend.fit;
chart.legend.fit = function fit() {
fitValue.bind(chart.legend)();
let top;
const marginTop = 30;
Object.defineProperty(this, 'top', {
get() {
return top + marginTop;
},
set(v) {
top = v;
},
});
this.height += 40;
};
},
};
The value 30 and 40 here are example values that you might want to adjust for you needs.
Keep in mind that since this is not a public API it might break in future releases but it works for me on chart.js 3.9.0
The ideal is that they add support for the full Padding object on options.plugins.legend.labels.padding config option so that you could use padding.top there. But currently only a single numeric value works