[Chartjs]-ChartJS 3+ x-axis only showing full moment object instead of just month

15👍

Your X axis scale was indeed invalid, you declared it as an array which is V2 syntax, in V3 all the scales are their own object where the key of the object is the scaleID. So removing the array brackets around the x axis scale object will resolve the issue.

Also your legend and tooltip config where wrong and in the wrong place, also V2 syntax.

For all changes please read the migration guide

const gainedChart = document.getElementById('gained-chart').getContext('2d');

const gain = [74.699997, 76.580002, 81.349998, 83.000000, 85.879997, 83.120003, 77.989998, 81.279999];
const dates = ["Jan 2, 20", "Feb 3, 20", "Mar 4, 20", "Apr 5, 20", "May 6, 20", "Jun 9, 20", "Nov 10, 20", "Dec 11, 20"];

let gainData = {
  datasets: [{
    label: "Gain (%)",
    data: gain,
    borderColor: 'rgba(255, 66, 66, 1)',
    backgroundColor: 'rgba(255, 66, 66, 1)',
    pointRadius: 1.2,
    pointBackgroundColor: 'rgba(255, 66, 66, 0.8)',
    pointHoverRadius: 6,
    pointHitRadius: 20,
    pointBorderWidth: 2,

  }]
};
let gainConfig = {
  plugins: {
    legend: {
      display: true,
      position: 'top',
      labels: {
        boxWidth: 80,
        color: 'black'
      },
    },
    tooltip: {
      callbacks: {
        label: function(tooltipItem, data) {
          return parseInt(tooltipItem.parsed.y)
        }
      }
    },
  },
  scales: {
    x: {
      type: 'time',
      time: {
        minUnit: 'month'
      }
    },
    y: {
      suggestedMax: 45,
      ticks: {
        stepSize: 5,
        //max: 100
      },
    },
  },
  maintainAspectRatio: false,
  responsive: true,
};
let lineGainChart = new Chart(gainedChart, {
  type: 'line',
  data: gainData,
  options: gainConfig,
  plugins: [{
    beforeInit: function(lineGainChart) {
      for (let c = 0; c < dates.length; c++) {

        let myMoment = moment(dates[c], 'MMM D, YYYY');

        lineGainChart.data.labels.push(myMoment);
      }
    }
  }]
});
<canvas class="graph-canvas" id="gained-chart" width="400" height="400"></canvas>

<script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>

Leave a comment