reactjschartschart.jsreact-chartjs-2

Change the Colour of the last segment of line chart in chartjs/react-chart2js


I want to change the colour of last segment of a line chart in react, i am using chartjs library,

import React from "react";
import { Line } from "react-chartjs-2";
import "../Styles/charitem.css";
import {
  Chart,
  LinearScale,
  CategoryScale,
  PointElement,
  LineElement,
} from "chart.js";
Chart.register(LinearScale, CategoryScale, PointElement, LineElement);

function ChartItem() {
  const last_element = (ctx, value) => {
    if (ctx.p0DataIndex === 0) {
      return value;
    }
    return undefined;
  };
  const historicalData = {
    labels: Array.from({ length: 7 }, (_, index) => getTimeLabel(index + 9, 0)),
    datasets: [
      {
        label: "Stock Price",
        data: Array.from({ length: 6 }, () => getRandomPrice(100, 250)),
        borderColor: "blue",
        backgroundColor: "rgba(0, 0, 255, 0.2)",
        tension: 0.4,
        segment: {
          borderColor: (ctx) =>
            last_element(ctx, "rgba(0, 0, 255, 0.2)") ||
            down(ctx, "rgba(255,0,0, 1)") ||
            "   rgba(0,128,0,1)",
        },
      },
    ],
  };

  return (
    <div className="chartitem-div">
      <Line data={historicalData} options={options} />
    </div>
  );
}

// Helper function to generate random price between min and max
function getRandomPrice(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Helper function to format time label
function getTimeLabel(hours, minutes) {
  return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(
    2,
    "0"
  )}`;
}

export default ChartItem;

I can do it for the first element using ctx.p0DataIndex in last_element function, how to access the last element of the array so that i can change its colour?


Solution

  • Even though I didn't use react-chartjs-2 to do this, I think it should help you.

    const lastSegment = function(ctx, value){
      if(ctx.p1DataIndex == config.data.datasets[0].data.length-1){
        return value
      }
    }
    
    segment: {
      borderColor: ctx => lastSegment(ctx, '#FF0000') 
    }
    

    I compare the index of the next point with the last index. If the 2 are equal, I change the colour of the segment to red.

    Here's the full code to see what it looks like