Chartjs-Render images as labels on Y axis

1๐Ÿ‘

โœ…

I adapted the code of this answer and came up with the following solution for your case.

const labels = ['Red Vans', 'Blue Vans', 'Green Vans', 'Gray Vans'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png']
  .map(png => {
    const image = new Image();
    image.src = png;
    return image;
  });
const values = [48, 56, 33, 44];

new Chart(document.getElementById("myChart"), {
  type: "horizontalBar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      yAxis.ticks.forEach((value, index) => {
        var y = yAxis.getPixelForTick(index);
        ctx.drawImage(images[index], xAxis.left - 40, y - 10);
      });
    }
  }],
  data: {
    labels: labels,
    datasets: [{
      label: 'My Dataset',
      data: values,
      backgroundColor: ['red', 'blue', 'green', 'lightgray']
    }]
  },
  options: {
    responsive: true,
    layout: {
      padding: {
        left: 50
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          display: false
        }
      }],
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment