chart.js

Any way to make Chartjs radar chart size independent of label lengths?


ChartJS automatically scales radar charts to fit the containing element. This ensures labels on the left and right are completely displayed.

However, if the rendered label lengths differ, this means that two otherwise identical charts will have different sizes for the actual chart "grid". This looks odd when they are placed together.

Is there a way to enforce a fixed size for the grid, independent of the text in the labels?

Can't see anything in the docs here: https://www.chartjs.org/docs/latest/axes/radial/linear.html


Solution

  • Got this solution making a custom plugin which worked. There appears to be no standard Chart.js option to fix the grid size.

    const fixedRadarRadius = {
      id: 'fixedRadarRadius',
      beforeLayout(chart, args, opts) {
        const r = chart.scales.r;
        if (!r) return;
        // Ensure Chart.js has sized the scale first
        // then override its radius to your fixed value
        r.afterFit = (scale) => { scale.drawingArea = opts.radius; };
      }
    };
    
    Chart.register(fixedRadarRadius);
    
    new Chart(ctx, {
      type: 'radar',
      data,
      options: {
        plugins: {
          fixedRadarRadius: { radius: 140 } // same radius for all charts
        },
        layout: { padding: { top: 24, right: 48, bottom: 24, left: 48 } },
        scales: { r: { beginAtZero: true, pointLabels: { padding: 4 } } }
      }
    });