[Chartjs]-Is that a way to marginTop a legend positioned on bottom of a Doughnut chartjs graph?

5πŸ‘

βœ…

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

Leave a comment