How do I prevent the scale labels from being cut o

2020-08-09 09:07发布

问题:

I am having a problem with chartjs where the scale labels are being "cut off" in the following way:

[1]

Is there a margin that can be set? I don't see anything in the chartjs documentation about this, and these seem to be contained within the chartjs canvas element (meaning: not covered by another div).

回答1:

Add scale label option with whitespace before value. 2 or more whitespaces is allowed.

scaleLabel: "<%= ' ' + value%>"


回答2:

You can also set a padding in the layout configuration (in chart.js 2 at least):

options: {
    layout: {
        padding: {
            left: 10
        }
    }
}

http://www.chartjs.org/docs/latest/configuration/layout.html



回答3:

Here's my hack - was scratching my head for a while until I found this post - thanks Jean-Baptiste Martin - your code lead me to this...

Given a dataset like [201, 203, 20004, etc.] - I grab the biggest and get length. 7 padding per character seems to work for me. length - 1 is to subtract 1 since the first character shows up fine for me - only need to add padding for all the other characters lopped off.

Hacky but this seems to work (on v 2.8) - I tested numbers up to like 40854385394 down to just single digits and it good enough for me!

options: {
  layout: { padding: { left: (this.data.reduce((a, b) => a > b ? a : b).toString().length - 1) * 7 } 
}


回答4:

The behavior of chart.js may have changed since this questions was originally posted. With v2.9.3, I only see this problem if the y-axis ticks include a mixture of integer & floating-point values. In this case (unfortunately my predominant case), the digits past the decimal point get clipped.

Below is what worked for me. In my solution, when there is a mixture of int & float, I just set a constant amount of padding (30px) to accommodate the floating-point digits; you may need a different value. Hopefully this helps some other soul avoid a day of struggle.

yAxes: [
    {
        ...
        ticks: {
            callback: (value, index, label_values) => {
                // Once per cycle through all the ticks, set the label padding appropriately
                // For unknown reasons sometimes chartjs passes a 1-point values array, which has no meaning. Ignore those.
                if (label_values.length > 1 && value === label_values[0]) {
                    // If labels have mixture of int & float, manually set the padding to give enough space for the decimal places.
                    const mixed_int_and_float_labels = label_values.some(v => Number.isInteger(v)) && !label_values.every(v => Number.isInteger(v));
                    this.chart.options.layout.padding.left = mixed_int_and_float_labels ? 30 : 0;
                }
                return value;
            }
        },
    }
]


标签: chart.js