[Vuejs]-How to sort yaxis label in range bar chart in vue-apexcharts?

-1👍

To sort the y-axis labels in ascending order, you can use the sort function to sort the data array that you’re passing to the chart component. Here’s an example:

<template>
  <div>
    <apexchart type="rangeBar" :options="options" :series="series"></apexchart>
  </div>
</template>

<script>
import VueApexCharts from 'vue-apexcharts'

export default {
  components: {
    apexchart: VueApexCharts,
  },
  data() {
    return {
      options: {
        plotOptions: {
          bar: {
            horizontal: true,
          },
        },
        xaxis: {
          categories: ['Category 1', 'Category 2', 'Category 3'],
        },
        yaxis: {
          labels: {
            formatter: function(val) {
              return val.split("~").shift();
            },
          },
        },
      },
      series: [
        {
          data: [
            {
              x: 'Category 1',
              y: ['05/23~05/30', '#FF0000'],
            },
            {
              x: 'Category 2',
              y: ['05/24~05/31', '#00FF00'],
            },
            {
              x: 'Category 3',
              y: ['05/25~06/01', '#0000FF'],
            },
          ],
        },
      ],
    };
  },
  mounted() {
    // Sort data array by y label
    this.series[0].data.sort((a, b) => {
      const [startA] = a.y[0].split('~');
      const [startB] = b.y[0].split('~');
      return new Date(startA) - new Date(startB);
    });
  },
};
</script>

In this example, I’m using the sort function on the series[0].data array in the mounted lifecycle hook to sort the data by the start date of the range (the first part of the y-axis label, before the ~ character). I’m using the split function to extract the start date and then using the Date constructor to transform it into a sortable value.

As for recommendations for other charting libraries for Vue.js, you can check out:

Leave a comment