score:4

Accepted answer

But it displays the value in the wrong position as it is in the image

That's because the indexes of the data you provided corresponds to the first 3 values of your labels.

Solution #1:

To resolve this, you have the even out the length of the labels to the length of your data set by providing placeholder values for the lacking points in your data.

Do not use zeros as placeholder for non-existent values in your dataset if you don't want Chartjs to display the chart data in this manner. [See the short grayed-out areas indicating the zero values.]

See the short grayed-out areas indicating the zero values.

So the better way to handle this is to provide null values instead. See working example below.

const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
const data = [{'x':'Apr', 'y':40},{'x':'July', 'y':70},{'x':'Dec', 'y':120}];

const filledMonths = data.map((month) => month.x);
const dataset = labels.map(month => {
  const indexOfFilledData = filledMonths.indexOf(month);
	if( indexOfFilledData!== -1) return data[indexOfFilledData].y;
  return null;
});
console.log(dataset);

Solution #2: In Chartjs > 2.x you can use time scale

If you have a lot of data and don't want to usey placeholder values for your missing data then you set your xAxes scale type as time in your chart options.

Here's an answer using this implementation.


score:-2

Chart.js supports all of the formats that Moment.js accepts ('MMM YYYY'). Just adding the year should do the trick.

score:0

If you don't have any value for any month, provide 0 as data for the same.

var options = {
            type: 'bar',
            data: {
                labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'],
                datasets:[
                    {
                        label: 'Test',
                        backgroundColor: 'red',
                        data: [0,0,0,40,0,0,70,0,0,0,0,120]
                    }
                ]
            },
            options: {
                responsive: true,
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: 'My Test'
                },
                scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
            }
        }
var ctx = document.getElementById('canvas').getContext('2d');
new Chart(ctx, options);

Related Query

More Query from same tag