Search code examples
javascriptchartschart.js

How to format Chart.js dates in the axes and tooltip


I have the following code that uses chart.js to generate a line graph. The Y axis represents price values, while the X axis represents date values. I want the dates on the X axis to display only the year, but I still want the full date to appear in the tooltip when hovering over a data point.

  const datesArray = ["1 May 2023", "2 May 2023", "3 May 2023", "4 May 2023", "5 May 2023"];
  const valuesArray = [107.71, 105.98, 106.12, 105.21, 106.215];

  const Chart = ({ width }) =>  (
    <ChartDiv style={{ width }} className='cursor-auto'>
      <PriceGraph 
         chartData={{ data: valuesArray, labels: datesArray }} 
         chartColour={'#218B82'} 
         chartFillColour={'#F2FFFF'} 
      />
    </ChartDiv>
  );
import React from 'react';
import { Line } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
import 'chartjs-adapter-date-fns';
Chart.register(...registerables);

const PriceGraph = ({ chartData, chartColour, chartFillColour }) => {
  const options = {
    scales: {
      x: {
        ticks: {
          display: true,
          callback: (value, index, values) => {
            const tickDate = new Date(value);
            return tickDate.getFullYear().toString();
          }
        }
      },
      y: {
        beginAtZero: true,
        ticks: {
          display: true,
        }
      }
    }
  }

  const data = {
    labels: chartData.labels,
    datasets: [
      {
        data: chartData.data,
        backgroundColor: chartFillColour,
        borderColor: chartColour,
        fill: true,
      }
    ]
  }

  return <Line data={chartData.labels ? data : null} options={options}/>;  
}

export default PriceGraph

When I run my code the tool tip reflects the correct date, however each tick on the X Axis displays "1970". I expect this is an issue with the data being input input in my callback function or the inappropriate use of a callback function.

Reviewing the chart.js documentation, there is an indication that I should use the type: time, and apply formatting. When I modify my code as follows I get a blank chart.

scales: {
      x: {
        type: 'time',
        time: {
          unit: 'year',
          tooltipFormat: 'dd MMM yyyy'
        },
        ticks: {
          display: true,
        }
      },

Any suggestions on how I should go about formatting my X axis?


Solution

  • For some reasons the parameters inside callback function are not populated as expected. Ideally first parameter value should be the value which is going to be print.

    The workaround for this would be to use your existing data and the index from the callback parameter. You can try the below code.

    callback: function(value, index, ticks) {
      const tickDate = new Date(chartData.labels[index]);
      return tickDate.getFullYear().toString();
    }