score:0

Accepted answer

the plugin core api offers a range of hooks that may be used for performing custom code. you can use the afterupdate hook to shift (offset) the x positions of the bars from the second dataset.

please have a look at your amended code below.

const offset = 22;
var mychart = new chart(document.getelementbyid('chart'), {
  type: 'bar',
  plugins: [{
    afterupdate: function(chart) {
      var dataset = chart.config.data.datasets[1];
      for (var i = 0; i < dataset._meta[0].data.length; i++) {
        var model = dataset._meta[0].data[i]._model;
        model.x += offset;
        model.controlpointnextx += offset;
        model.controlpointpreviousx += offset;
      }
    }
  }],
  data: {
    labels: ['red', 'blue', 'orange', 'green'],
    datasets: [{
      label: 'vote share now',
      data: [25.5, 22.7, 8.6, 5.5],
      backgroundcolor: [
        'rgba(250,0,0,0.7)',
        'rgba(0,17,255, 0.7)',
        'rgba(255,155,0, 0.7)',
        'rgba(0,255,9,0.7)'
      ],
      categorypercentage: 0.8,
      barpercentage: 0.9,
      xaxisid: "now",
    }, {
      label: 'vote share then',
      data: [22.5, 29.7, 10.3, 5.3],
      backgroundcolor: [
        'rgba(250,0,0,0.2)',
        'rgba(0,17,255,0.2)',
        'rgba(255,115,0,0.2)',
        'rgba(0, 255,9,0.2)'
      ],
      categorypercentage: 0.6,
      barpercentage: 0.6,
      xaxisid: "then",
    }]
  },
  options: {
    responsive: false,
    legend: {
      onclick: null
    },
    scales: {
      xaxes: [{
          id: "now",
          gridlines: {
            display: false
          }
        },
        {
          id: "then",
          offset: true,
          display: false
        }
      ],
      yaxes: [{
        ticks: {
          min: 0,
          max: 50,
          stepsize: 10,
          callback: function(value, index, values) {
            return value + '%';
          }
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.9.3/chart.min.js"></script>
<canvas id="chart" height="200"></canvas>


Related Query

More Query from same tag