Search code examples
chartslocationchart.js

How to specify ticks locations in chart.js?


I am looking for a way to manually specify x/y ticks locations on a chart.js chart, an equivalent of matplotlib's matplotlib.pyplot.xticks. The documentation explains how to create custom tick formats, but this works on automatically calculated tick locations. How can I specify the ticks locations?

This is the config that I am using:

var config = {
    type: "line",
    data: {
        labels: [],
        datasets: [{
            data: [{x: 1, y: 2}, {x: 5, y: 3}, {x: 6, y: 4}],
            fill: false,
            borderColor: "#1f77b4",
        }],
    },
    options: {
        scales: {
            xAxes: [{
                type: 'linear',
                distribution: 'series',
                ticks: {
                    min: 0.,
                    max: 7.,
                },
            }]
        },
    },
}

which produces this file: chart

I would like to specify xticks locations, e.g. [0., 3.5, 5.7, 6.1], so that the plot would look more like (not taking into account grid lines and smooth plot line):

mpl


Solution

  • Apparently with Chart.js v3, the accpted solution no longer works as expected. Trying afterBuildTicks as suggested by b1000 in his comment, it also didn't work.

    To make it work with afterBuildTicks, you need to map the number values into objects that have the property value each ([{ value: 0 }, { value: 3.5 }, ... ]). This can be done as follows:

    afterBuildTicks: axis => axis.ticks = [0, 3.5, 5.7, 6.1].map(v => ({ value: v })) 
    

    Please take a look at below runnable sample:

    new Chart('line-chart', {
      type: 'scatter',
      data: {
        datasets: [{
          data: [{x: 1, y: 2}, {x: 5, y: 3}, {x: 6, y: 4}],
          showLine : true,
          borderColor: '#1f77b4',
        }]
      },
      options: {
        scales: {
          x: {    
            min: 0,
            afterBuildTicks: axis => axis.ticks = [0, 3.5, 5.7, 6.1].map(v => ({ value: v })) 
          }
        }
      }
    });
    canvas {
      max-height: 180px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
    <canvas id="line-chart"></canvas>