[Chartjs]-How to add padding between Graph and X/Y-Scale in chart.js?

2👍

Actually you don’t need all the complexity from the linked solution because

  1. You intend to not show the axes lines (I see from the image that you will set the chart background and the scale color to be the same) and
  2. You’ve already hardcoded the scale start and end values (by which I assume you know the range of values your data will be in and don’t need it autocalculated) – see the alternative solution if this condition doesn’t hold for you

With those caveats, you just need to make a few changes (just Ctrl + F on the option name to find the line to replace)

scaleSteps: 5,
// Number - The value jump in the hard coded scale
scaleStepWidth: 50,
// Number - The scale starting value
scaleStartValue: -50,

We’re basically starting the scale to start from a value 1 step lower than what we need. This lifts up the graph. Now all we need to do is hide this extra scale label, which we do with

scaleLabel: function (d) {
    if (d.value < 0)
        return '';
    else
        return d.value + '         ';
},

The first line in the method takes care of hiding the extra scale label. The + ' ' on the last line moves the graph to the right (we tell Chart.js that the labels are longer than they really are)


Fiddle – http://jsfiddle.net/56578cn4/


enter image description here


If 2. doesn’t apply, remove the scaleOverride and configuration and override the common method that calculates the y axis scale range before you initialize the chart to add one scale label above and one below

// this applies to all chart instances that use this scale!
var originalCalculateScaleRange = Chart.helpers.calculateScaleRange;
Chart.helpers.calculateScaleRange = function () {
    var scaleRange = originalCalculateScaleRange.apply(this, arguments);
    // add 1 unit at the top and bottom
    scaleRange.min = scaleRange.min - scaleRange.stepValue;
    scaleRange.max = scaleRange.max + scaleRange.stepValue;
    scaleRange.steps = scaleRange.steps + 2;
    return scaleRange;
}

This will work fine assuming you don’t mind the extra labels when the values are all above 0 (our scaleLabel option takes care of hiding negative labels, and negative labels only).

Note that if you are using other charts where you don’t want this to apply you’ll need to revert this after you are done initializing your chart.


Fiddle – http://jsfiddle.net/mkzdzj3b/

Leave a comment