Chartjs-How to create chart with two DataSeries with different labels?

0πŸ‘

βœ…

It is maybe not the most elegant solution, but you could:

  1. Create the labels, by collecting them all together (removeing the duplicates using a "set conversion")
  2. Transform the datasets to define the value/position in the chart
  3. set the property spanGaps to avoid gaps.

Here a short demo with the provided data:

let DataSet_1 = {'2020': 6, '2021': 8, '2022': 10}
let DataSet_2 = {'2017': 5, '2019': 4, '2020': 9, '2022': 11}

// creates, lables, remove duplicates,
let labels =  [...new Set([ ...Object.keys(DataSet_1), ...Object.keys(DataSet_2) ])]
  .sort()

let converted_1 = labels.map( key => ({ x: key, y: DataSet_1[key]}));
let converted_2 = labels.map( key => ({ x: key, y: DataSet_2[key]}));

var options = {
    type: 'line',
    data: {
        datasets: [{
            type: 'line',
            label: 'DataSet_1',
            data: converted_1
        }, {
            type: 'line',
            label: 'DataSet_2',
            data: converted_2,
        }],
        labels: labels
    },
    maintainAspectRatio: false,
    legend: { display: false },
    options: {
        spanGaps: true,
    }
}

const chart = document.getElementById('chart1')
new Chart(chart, options);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div style="width:500px;height:184px">
   <canvas id="chart1" width="500" height="184"></canvas>
<div>

Leave a comment