Chartjs-ChartJS multiple datasets but with single bar chart

0👍

It’s a tricky use case. I’m adding a snippet where you have 1 dataset per data (and not only 2). The data are stored in the datasets by a data point. There are the definition of X axes as well in order to avoid the behavior for category+bar chart.

const data = {
  datasets: [{
    label: 'Volumi',
    data: [{x: 1, y: 60000}],
    backgroundColor: 'rgba(255, 26, 104, 0.2)',
    borderColor: 'rgba(255, 26, 104, 1)',
    borderWidth: 1,
    xAxisID: "x1",
    categoryPercentage: 1
  },
  {
    label: 'euro',
    data:[{x: 2, y: 500000}],
    backgroundColor: 'rgba(54, 162, 235, 0.2)',
    borderColor: 'rgba(54, 162, 235, 1)',
    borderWidth: 1,
    xAxisID: "x1",
    yAxisID: "y1",
    categoryPercentage: 1
  },
  {
    label: 'euro',
    data:[{x: 3, y: 200000}],
    backgroundColor: 'rgba(255, 206, 86, 0.2)',
    borderColor: 'rgba(255, 206, 86, 1)',
    borderWidth: 1,
    xAxisID: "x1",
    yAxisID: "y1",
    categoryPercentage: 1
  },
  {
    label: 'euro',
    data:[{x: 4, y: 300000}],
    backgroundColor: 'rgba(75, 192, 192, 0.2)',
    borderColor: 'rgba(75, 192, 192, 1)',
    borderWidth: 1,
    xAxisID: "x1",
    yAxisID: "y1",
    categoryPercentage: 1
  },
  {
    label: 'euro',
    data:[{x: 5, y: 100000}],
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
    borderColor: 'rgba(0, 0, 0, 1)',
    borderWidth: 1,
    xAxisID: "x1",
    yAxisID: "y1",
    categoryPercentage: 1
  }
  ]
};

const config = {
  type: 'bar',
  data,
  options: {
    plugins: {
      legend: false,
      tooltip: {
        callbacks: {
          title(tooltipItems){
            if (tooltipItems.length) {
              const item = tooltipItems[0];
              const tick = item.chart.scales.x.ticks[item.datasetIndex]; 
              return tick.label;
            }
          }
        }
      }
    },
    scales: {
      x: {
        labels: ['Volume', 'Manutenzione', 'Professionals', 'Materie', 'Cleaning'],
      },
      x1: {
        display: false,
        offset: true
      },
      y: {
            suggestedMin: 0,
            suggestedMax: 120000,
            beginAtZero: true,
            min: 0,
            grid: {
               drawOnChartArea: false
            }
          },
      y1: {
            suggestedMin: 0,
            suggestedMax: 1000000,
            beginAtZero: true,
            min: 0,
            position: 'right'
          }
      }
  }
};

const ctx = document.getElementById("myChart");
const myChart = new Chart(ctx, config);
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment