0

I am using Chart.js to create a horizontal bar chart as shown below. The y axis has three labels: A, B, C. How do I style those vertical labels individually? For example, I may want to have one or two of those labels bolded and/or red.

I looked at this answer: https://stackoverflow.com/a/65463614/3851085. However, that is a solution for the x-axis. For the y-axis, there needs to be a different solution to compute the x pixel of each label.

The code snippet is with an older version of Chart.js, but I am actually using the latest version.

<html>

<head>
  <title>Horizontal Bars</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
</head>

<body>
  <div>
    <canvas id="canvas" height="100"></canvas>
  </div>
  <script>
    window.onload = function() {
      var ctx = document.getElementById('canvas').getContext('2d');
      window.myBar = new Chart(ctx, {
        type: 'horizontalBar',
        data: {
          labels: ['A', 'B', 'C'],
          datasets: [{
            data: [[1, 3], [4, 5], [2, 6]],
            backgroundColor: 'lightblue'
          }]
        },
        options: {
          responsive: true,
          legend: {
            display: false,
          }
        }
      });
    };
  </script>
</body>

</html>
Software Dev
  • 910
  • 3
  • 10
  • 27

1 Answers1

1

The documentation is unclear about that, but you can use arrays in options to configure labels.

Here is your code, refactored to be compatible with Chart.js 4.2.0:

window.onload = function() {
  var ctx = document.getElementById('myChart').getContext('2d');
  window.myBar = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['A', 'B', 'C'],
      datasets: [{
        data: [[1, 3], [4, 5], [2, 6]],
        backgroundColor: 'lightblue'
      }]
    },
    options: {
      responsive: true,
      indexAxis: 'y',
      scales: {
        y: {
          ticks: {
            color: ['#ff0000', '#000000', '#000000'],
            font: {
              weight: ['bold', 'bold', 'normal']
            }
          }
        }
      },
      plugins: {
        legend: {
          display: false
        } 
      }
    }
  });
};
.chart-container {
  position: relative;
  height: 90vh;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.2.0"></script>

<div class="chart-container">
  <canvas id="myChart"></canvas>
</div>
Badacadabra
  • 8,043
  • 7
  • 28
  • 49