[Chartjs]-How to create a chart that uses strings for both the X and Y axes?

3👍

Finally I got the solution after many trial-and-errors. I have to say that the documentation of chart.js is quite unclear and should be improved.

My findings are:

  • xLabels and yLabels approach is not working. There are no clear documentation on these two parameters.
  • Don’t care about setting the type to category. chart.js only accepts numerical values; you have to map the values to strings by using your own callback method.
var options = {
    type: "line",
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June'],
        datasets: [{
            label: "My First Dataset",
            data: [1, 2, 3, 1, 1, 1],
            fill: false,
            borderColor: "rgb(75, 192, 192)",
            lineTension: 0.1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    max: 3,
                    min: 1,
                    stepSize: 1,
                    callback: function(label, index, labels) {
                        switch (label) {
                            case 1:
                                return 'A';
                            case 2:
                                return 'B';
                            case 3:
                                return 'C';
                        }
                    }
                }
            }]
        }
    }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>

Leave a comment