[Chartjs]-ChartJS bar chart with legend which corresponds to each bar

11👍

The way to do this, to create multiple items in the datasets, each having data for only one category. You can have one top level label called stock and then create the individual data-sets for each type.

// create a chart.
const ctx = canvas.getContext("2d");
const chart = new Chart(ctx, {
   type: "horizontalBar",
   data: {
      labels: ["Stock"],
      datasets: [{
         label: "Apples",
         backgroundColor: "#AF7",
         data: [Math.random() * 100],
      },{
         label: "Oranges",
         backgroundColor: "#FA4",
         data: [Math.random() * 100],
      },{
         label: "Mangos",
         backgroundColor: "#FF7",
         data: [Math.random() * 100],
      },{
         label: "Avocados",
         backgroundColor: "#2A7",
         data: [Math.random() * 100],
      }]
   },
   options: {
          responsive: false,
          legend: { position: 'top'},
          title: { display: true, text: 'Fruit in stock'}
      }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id=canvas height=200 width=500></canvas>

Leave a comment