Chartjs-Chart.js change colour of line chart graph based on previous values

0👍

it’s not exactly the same as your requirement, but results in kinda similar output,

enter image description here
logic: separated the points into two lines, and plotted both on the graph,

you can tune some graph settings to get the same view.

    let redLine = [];
    let greenLine = [];
    let points = [
      { x: 1, y: 1 },
      { x: 2, y: 2 },
      { x: 3, y: 1 },
      { x: 4, y: 5 },
      { x: 5, y: 2 },
      { x: 6, y: 5 },
      { x: 7, y: 8 },
      { x: 8, y: 9 },
      { x: 9, y: 2 },
      { x: 10, y: 1 },
      { x: 11, y: 9 },
      { x: 12, y: 6 },
      { x: 13, y: 7 },
      { x: 14, y: 3 },
      { x: 15, y: 6 },
    ];
    points.forEach((point, index) => {
      let isIncreasing = false;
      if (index > 0) {
        isIncreasing = point.y > points[index - 1].y;
        (isIncreasing ? redLine : greenLine).push(NaN);
        greenLine.push(point);
        redLine.push(point);
      } else {
        // index === 1 && (isIncreasing ? greenLine : redLine).push(points[0]);
        greenLine.push(point);
        redLine.push(point);
      }
    });

const data = {
  datasets: [
  {
    data: greenLine,
    backgroundColor: 'rgb(165, 95, 0,0.3)',
    borderColor: 'rgb(0, 255, 0)',
    borderWidth: 1,
    showLine: true,
    spanGaps: false,
    fill: "start",
    tension:0.2
  },
  {
    data: redLine,
    backgroundColor: 'rgb(165, 95, 0,0.3)',
    borderColor: 'rgb(255, 0, 0)',
    borderWidth: 1,
    showLine: true,
    spanGaps: false,
    fill: "start",
    tension:0.2
  }],
};
const config = {
  type: 'scatter',
  data: data,
  options: {
    scales: {
      x: {
        type: 'linear',
        position: 'bottom'
      }
    }
  }
};

0👍

You can use segments for this:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      segment: {
        borderColor: (ctx) => (ctx.p0.parsed.y < ctx.p1.parsed.y ? 'green' : 'red')
      }
    }]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
</body>

Leave a comment