Chart.js icon indicating copy to clipboard operation
Chart.js copied to clipboard

Cannot add padding when legend is aligned left

Open elinake opened this issue 1 year ago • 2 comments

Expected behavior

I want my legend in the top left corner with padding on the left

 plugins: {
        legend: {
          display: true,
          align: 'start',
          title: {
            display: true,
            padding: {
              left: 20
            }
          }
        }
      }

Current behavior

padding: { left: 20 } has no effect, and padding: 20 only adds padding to top. Issue seems to have been fixed for some configurations since a related ticket was closed, but my configuration is not working.

Reproducible sample

https://codepen.io/elinakeranen/pen/dygewgo

Optional extra steps/info to reproduce

No response

Possible solution

No response

Context

No response

chart.js version

v.4.3.0

Browser name and version

No response

Link to your project

No response

elinake avatar May 11 '23 13:05 elinake

@elinake the padding options you are using is related to legend title and not to the legend itself. Therefore, maybe I'm wrong, this is not a bug but a missing feature. The padding to the legend title is working in the same way of the title entity, therefore only top and bottom are used. Maybe the doc about legend title padding could be changed.

stockiNail avatar Jun 07 '23 17:06 stockiNail

@elinake as workaround, you can add a plugin and change the position of the legend.

Steps:

  1. create a custom plugin implementing afterUpdate hook
  2. change the chart.legend.left property
  3. change all legendHitBoxes left property.

Plugin code:

var myChart = new Chart(ctx, {
  type: 'line',
  plugins: [{
    id : 'legendOffset',
    afterUpdate(chart) {
      const legend = chart.legend;
      legend.left += 20;
      for (const box of legend.legendHitBoxes) {
        box.left += 20;
      }
    }
  }],
  data: {
  ....

Codepen: https://codepen.io/stockinail/pen/vYQEEjR

stockiNail avatar Jun 08 '23 05:06 stockiNail