Search code examples
highchartslabelaxis

Show only first and last xAxis label in Highcharts


I would like to display only the first and the last label on my xAxis. This would give enough of a »frame« for the user. However, I don't succeed in it. I am working with a synchronized chart, which can be found here. Is the second and third »column« of (smaller) graphs, I am targeting at.

I tried to work with »startOnTick« and »endOnTick«, but it won't do it.

    xAxis: {
      crosshair: true,
      events: {
        setExtremes: syncExtremes
      },
      visible: i === 1,
      showFirstlabel: true,
      showLastlabel: true,
      startOnTick: true,
      endOnTick: true,
      labels: {
        step: 500,
        format: '{value}'
      }
    },

What is the correct way to force Highcharts to display only first and last label?

Here is a short fiddle (don't know why the line does not appear; it shows the values with mouseover...).

Thanks for any hints.


Solution

    • You can use the xAxis.labels.formatter callback to show wanted ticks:

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

        xAxis: {
        tickAmount: 10,
            labels: {
            formatter() {
            if(this.isFirst || this.isLast) {
                return this.value
            } else {
                return ''
            }
          }
        }
      },
    

    API: https://api.highcharts.com/highcharts/xAxis.labels.formatter

    • If you want to have more control about it (like hide label and tick) you can use the load callback method and proper logic to hide/show ticks:

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

      chart: {
        events: {
          load() {
            let chart = this;
    
            for (let i in chart.xAxis[0].ticks) {
                //hide all
              chart.xAxis[0].ticks[i].label.hide()
              chart.xAxis[0].ticks[i].mark.hide()
                        // show first and last tick
              if (chart.xAxis[0].ticks[i].isFirst || chart.xAxis[0].ticks[i].isLast) {
                chart.xAxis[0].ticks[i].mark.show()
                chart.xAxis[0].ticks[i].label.show()
              }
            }
          }
        }
    

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