Chartjs-Display Time values on line chart Y axis with React Chart.js

0👍

Here’s an updated version of your getChartData function that handles the conversion and formatting:

function formatTime(totalTime) {
  const hours = Math.floor(totalTime / 3600);
  const minutes = Math.floor((totalTime % 3600) / 60);
  const seconds = totalTime % 60;

  return `${hours.toString().padStart(2, '0')}:${minutes
    .toString()
    .padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

function getChartData(documents, label, color) {
  const chartData = {
    labels: [],
    datasets: [
      {
        label: label,
        data: [],
        backgroundColor: color,
        borderColor: color,
        borderWidth: 1,
      },
    ],
  };

  documents.forEach((document) => {
    const timeComponents = document.totaltime.split(':');
    const hours = parseInt(timeComponents[0]);
    const minutes = parseInt(timeComponents[1]);
    const seconds = parseInt(timeComponents[2]);

    // Calculate the total time in seconds
    const totalTimeInSeconds = hours * 3600 + minutes * 60 + seconds;

    // Format the time as hours:minutes:seconds
    const formattedTime = formatTime(totalTimeInSeconds);

    chartData.labels.push(formattedTime);
    chartData.datasets[0].data.push(totalTimeInSeconds);
  });

  return chartData;
}

0👍

Solution to get the time values without replacing your date labels after using Remesh’s answer

Send the formattedDate labels to the line chart component:

  const chartData = {
    labels: [],
    datasets: [
      {
        label: label,
        data: [],
        backgroundColor: color,
        borderColor: color,
        borderWidth: 1,
        value: formattedDates
      },
    ],
  };

access it in the line component and change the tick values using a callback:

  return (
    <div>
      <Line 
        data={data}
        type="line"
        height={300} // set the height of the chart
        width={1300} // set the width of the char
        options= {{
          scales: {
              x: {
                  ticks: {
                      // add dates to x axis
                      callback: function(index) {
                          return data.datasets[0].value[index];
                      }
                  }
              }
          }
        }}
      />
    </div>
  );
}

Leave a comment