Chartjs-Grouped bar chart having each group with different data using chart.js

1πŸ‘

βœ…

Yes you can use the datalabels plugin to achieve what you want:

Example:

Chart.register(ChartDataLabels); 

var options = {
  type: 'bar',
  data: {
    labels: ["Category 1", "Category 2", "Category 3"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3],
        animals: ['cat', 'dog', 'bear'],
        borderWidth: 1,
        backgroundColor: ['orange', 'blue', 'gray']
      },
      {
        label: '# of Points',
        data: [7, 11, 5],
        animals: ['monkey', 'bird', 'fish'],
        borderWidth: 1,
        backgroundColor: ['yellow', 'cyan', 'purple']
      }
    ]
  },
  options: {
    plugins: {
        title: {
        display: true,
        text: 'title'
      },
      datalabels: {
          anchor: 'end', // remove this line to get label in middle of the bar
          align: 'end',
          formatter: (val, x) => (x.dataset.animals[x.dataIndex]),
          labels: {
            value: {
              color: 'purple'
            }
          }

        }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc"></script>
</body>

-1πŸ‘

you can use Plotly.js for grouped chart please check below code

Reference URL : https://plotly.com/javascript/bar-charts/

var trace1 = {
  x: ['giraffes', 'orangutans', 'monkeys'],
  y: [20, 14, 23],
  name: 'SF Zoo',
  type: 'bar'
};

var trace2 = {
  x: ['giraffes', 'orangutans', 'monkeys'],
  y: [12, 18, 29],
  name: 'LA Zoo',
  type: 'bar'
};

var data = [trace1, trace2];

var layout = {barmode: 'group'};

Plotly.newPlot('myDiv', data, layout);
<head>
    <!-- Load plotly.js into the DOM -->
    <script src='https://cdn.plot.ly/plotly-1.58.4.min.js'></script>
</head>

<body>
    <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>

Leave a comment