Alvaro
Alvaro

Reputation: 41595

Prevent Highchart.js from cutting xAxis label

I want to only show the first and last label for the xAxis. Then, I want to show it without rotation and in a single line. And when I do this, this happens and the last label gets cut when there are many columns or the width of the viewport is small.

enter image description here

Demo online: https://jsfiddle.net/8esnf4dj/

This is my xAxis config:

xAxis: {
      categories: [....],
      labels: {
          rotation: 0,
          style: {
            textOverflow: 'none',
            whiteSpace: 'nowrap'
          },
     }
}

Is there any way to align the text in a way that this won't happen?

I've seen that this can be fixed by adding chart.marginRight but I would rather prefer not to "lose" that space not the right and just align the text in a way that will always be visible.

Upvotes: 0

Views: 837

Answers (2)

Sebastian Wędzel
Sebastian Wędzel

Reputation: 11633

I am not sure if it is possible to achieve it by using only API options, because all the labels are rendered in the center of the tick, but you can move/set the position of each label 'manually'.

    events: {
        render() {
            const chart = this;
            const xAxis = chart.xAxis[0];
            const lastTickPosition = xAxis.tickPositions.length - 1;
            const lastLabel = chart.xAxis[0].ticks[lastTickPosition].label;
            
            lastLabel.translate(-lastLabel.getBBox().width/ 4, 0)
        }
    }

Demo: https://jsfiddle.net/BlackLabel/kbn7zwfc/

API: https://api.highcharts.com/highcharts/chart.events.render

Upvotes: 2

Shubham Periwal
Shubham Periwal

Reputation: 2248

You can use "align: right" Read the usage of align to understand why this works. Basically this would mean that the bar would align to the rightmost end of the label so the label always fits

xAxis: {
      categories: [....],
      labels: {
          rotation: 0,
          align: "right",
          style: {
            textOverflow: 'none',
            whiteSpace: 'nowrap'
          },
     }
}

Upvotes: 0

Related Questions