[Chartjs]-Chartjs 3.x – How to duplicate X axis on both sides of horizontal bar chart with only 1 dataset?

1πŸ‘

In case you want the see the same ticks at the top of the chart, simply define a second x-axis as follows:

x1: {
  position: 'top'
}

Please take a look at below runnable code and see how it works:

new Chart('myChart', {
  type: 'line',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F'],
    datasets: [{    
      data: [1, 3, 6, 2, 8, 9],
      borderColor: '#00D',
    }]
  },
  options: {
    scales: {
      x: {
      },
      x1: {
        position: 'top'
      }
    }
  }
});
canvas {
  max-height: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

0πŸ‘

In case you want to produce a horizontal bar chart, you could define the x-axes as follows:

scales: {
  x: {
    min: 0
  },
  x1: {
    position: 'top',
    min: 0,
    max: 9
  }
}

Please take a look at the runnable sample below and see how it works when the data is dynamic:

var data = [3, 6, 8, 9, 31];

new Chart('myChart', {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E'],
    datasets: [{
      data: data,
      borderColor: '#00D',
    }]
  },
  options: {
    indexAxis: 'y',
    plugins: {
      legend: {
        display: false
      }
    },
    scales: {
      x: {
        min: 0
      },
      x1: {
        position: 'top',
        min: 0,
        suggestedMax: Math.max(...data)
      }
    }
  }
});
canvas {
  max-height: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

Leave a comment