Mike Barwick
Mike Barwick

Reputation: 5367

Chart.js v2, remove padding/margin from radar chart

Has anyone run into the issue of removing padding (or margin?) from a chartjs chart?

Below is my code (in jsFiddle)...and image (notice the bottom? UGLY sauce).

Here's a JSFiddle that highlights the issue. Notice the padding at the bottom of the white box. https://jsfiddle.net/mre1p46x/

enter image description here

Upvotes: 1

Views: 3659

Answers (1)

potatopeelings
potatopeelings

Reputation: 41065

You can wrap a bit of logic around the fit method using the beforeFit and afterFit handlers to correct this padding when the number of labels is 3 (the fit function starts off by assuming a maximum radius of half the chart height. For a triangle, we actually have a bit more space)

All we do is scale the height property to compensate for this assumption, like so

...
options: {
    scale: {
        beforeFit: function (scale) {
            if (scale.chart.config.data.labels.length === 3) {
                var pointLabelFontSize = Chart.helpers.getValueOrDefault(scale.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize);
                scale.height *= (2 / 1.5)
                scale.height -= pointLabelFontSize;
            }
        },
        afterFit: function (scale) {
            if (scale.chart.config.data.labels.length === 3) {
                var pointLabelFontSize = Chart.helpers.getValueOrDefault(scale.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize);
                scale.height += pointLabelFontSize;
                scale.height /= (2 / 1.5);
            }
        },
            ...

The scaling factor 2 / 1.5 is pretty easy to figure out

  1. With h = distance from center of triangle to a corner
  2. Total height of the triangle = h + distance from center of triangle to a side = h + h * sin 30 = 1.5 h
  3. h currently = chart height / 2
  4. We want to scale this by r, such that

    1.5 * chart height / 2 * r = chart height

  5. This gives us

    r = 2 / 1.5


Fiddle - https://jsfiddle.net/zqp525gf/

Upvotes: 3

Related Questions