Home > front end >  Set Y axis at the top of each bar using Chart.js library
Set Y axis at the top of each bar using Chart.js library

Time:10-17

I have a horizontal bar chart, my desire result is like this photo using enter image description here

This is the following code for that:

TS:

 createAreaChart() {
this.barChart1 = document.getElementById('barChart1');
this.ctx1 = this.barChart1.getContext('2d');

 let i = 0;
this.data1.forEach(div => {
  if(i==0){
    this.backgroundColors.push('#A60A2D');
  } if(i==1) {
    this.backgroundColors.push('#00A2C3');
  } if(i==2) {
    this.backgroundColors.push('#434F55');
    i = -1;
  }
  i  ;
});

this.chart1 = new Chart(this.ctx1, {
      type: 'horizontalBar',
      data: {
        labels: this.data1.map(r => r.icon),
        datasets: [{
          data: this.data1.map(r => r.total),
          label: 'Annual Cost',
          backgroundColor: this.backgroundColors,
          borderColor: this.backgroundColors,
          borderWidth: 1
        }]
      },
      options: {
        legend: {
          display: false
        },
        tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              var value = data.datasets[0].data[tooltipItem.index];
              if (parseInt(value) >= 1000) {
                return '$'   value.toFixed(2).toString().replace(/\B(?=(\d{3}) (?!\d))/g, ",");
              } else {
                return '$'   value.toFixed(2).toString();
              }
            }
          }
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true,
              precision: 2,
              userCallback : function(value, index, values) {
                if(parseInt(value) >= 1000){
                  return '$'   value.toString().replace(/\B(?=(\d{3}) (?!\d))/g, ",");
                } else {
                  return '$'   value;
                }
              }
            }
          }]
        }
      }
    });
    this.chart1.height = 225;

    }

HTML

<div >
      <div >
        <div >Test</div>
      </div>
      <div >
        <div >
          <canvas id="barChart1" height="220px"></canvas>
        </div>
      </div>
    </div>

Result

enter image description here

I need to place the Y-axis text above each bar, how can I achieve that?

As other answers I try to use:

layout: {
        padding: {
          left: 0,
          right: 0,
          top: 15,
          bottom: 0
        }
      }

OR

plugins: {
        datalabels: {
          anchor: 'end',
          align: 'top',
          formatter: Math.round,
          font: {
            weight: 'bold'
          }
        }
      }

But it didn't work, what do I need to do to achieve the desired result?

CodePudding user response:

This can be done mainly through different options of the scales.yAxes.ticks option.

For further details, consult Tick Configuration from the Chart.js v2.9.4 documentation.

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

new Chart('myChart', {
  type: 'horizontalBar',
  data: {
    labels: ['One', 'Two', 'Three'],
    datasets: [{
      data: [8, 12, 7],
      backgroundColor: ['#A60A2D', '#00A2C3', '#434F55'],
      barPercentage: 0.6
    }]
  },
  options: {
    responsive: false,
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        gridLines: {
          drawOnChartArea: false
        },
        ticks: {
          min: 0
        }
      }],
      yAxes: [{
        gridLines: {
          display: false
        },
        ticks: {
          mirror: true,
          fontSize: 18,
          labelOffset: -22
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related