How can I change ChartJS line color based on the value?

zen

I am trying to do the same thing provided in this SO answer, https://stackoverflow.com/a/66943726/1108057

Unfortunately that answer is for older versions of Chart.js and a lot of the needed elements are not supported in the new version, such as accessing _meta properties directly.

I was able to figure out how to get meta of the dataset in the new version, but I can't figure out the remaining part of it as I don't know what it was referencing in the previous version.

plugins: [{
    id: 'redLineLoss',
    beforeRender: (x, options) => {
        const c = x;
        const dataset = x.data.datasets[1];
        const yScale = x.scales['y'];
        const yPos = yScale.getPixelForValue(0);

        const gradientFill = c.ctx.createLinearGradient(0, 0, 0, c.height);
        gradientFill.addColorStop(0, 'rgb(86,188,77)');
        gradientFill.addColorStop(yPos / c.height, 'rgb(86,188,77)');
        gradientFill.addColorStop(yPos / c.height, 'rgb(229,66,66)');
        gradientFill.addColorStop(1, 'rgb(229,66,66)');

        const datasetMeta = x.getDatasetMeta(1);

        console.log(datasetMeta['data']);

        // STUCK HERE -- what do I get from the dataset meta now?

        //console.log(datasetMeta.dataset.getProps(['x', 'y']));

        //console.log(model[Object.keys(x.getDatasetMeta(1))]);

        //const model = x.data.datasets[1]._meta[Object.keys(dataset._meta)[1]].dataset._model;

        //model.borderColor = gradientFill;
    },
}],

I want to only apply this to a specific dataset in the chart, not all of them. That's why I am selecting the dataset with key 1.

rozsazoltan

Solution # 1

The pointBorderColor and pointBackgroundColor work perfectly when you only want to color the markers of the values. To do this, you need to predefine an array of colors from the array of values.

You can color the borderColor or backgroundColor of a line chart on a segment-by-segment basis. For this, you have the option of using segment.borderColor or segment.backgroundColor (when fill: true is set). These settings invoke a function to which you pass the current opening and closing values of the "segment". I have written an example that includes these as well, although I had to define the 0 value here to ensure that the segment consists only of positive or negative numbers... anyway, here is the example:

Chart.js Github Issue #1493

const ctx = document.getElementById("myChart").getContext("2d")
const data = [10, 20, 0, -10, -20, 0, 5]
const colors = data.map((value) => value < 0 ? 'red' : 'green')

const chart = new Chart(ctx, {
  type: "line",
  data: {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
    datasets: [{
      label: "Sample Dataset",
      data: data,
      fill: true, // set true for "backgroundColor" using
      segment: {
        borderColor: (part) => {
          const prevValue = part.p0.parsed.y // start value
          const nextValue = part.p1.parsed.y // end value
          return prevValue < 0 || nextValue < 0 ? "red" : "green" // return with a color by rule
        },
        backgroundColor: (part) => {
          const prevValue = part.p0.parsed.y // start value
          const nextValue = part.p1.parsed.y // end value
          return prevValue < 0 || nextValue < 0 ? "red" : "green" // return with a color by rule
        },
      },
      pointBorderColor: colors, // with array of colors
      pointBackgroundColor: colors, // with array of colors
    }]
  },
  options: {
    responsive: true,
    scales: {
      y: {
        ticks: {
          beginAtZero: true
        }
      }
    }
  },
})
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<canvas id="myChart"></canvas>

Solution # 2

To achieve gradient fill in Chart.js 3.x or higher versions, you can use the package called chartjs-plugin-gradient available at. I have provided a simple example code below:

const ctx = document.getElementById("myChart").getContext("2d")
const gradient = window['chartjs-plugin-gradient'] // call CDN "chartjs-plugin-gradient"

const chart = new Chart(ctx, {
  type: "line",
  data: {
    labels: ["Jan", "Feb", "Mar", "Apr", "May"],
    datasets: [{
      label: "Sample Dataset",
      data: [0, 1, 4, 16, 64],
      fill: true, // set true for "backgroundColor" using
      gradient: {
        // Can set gradient background (need "fill: true")
        backgroundColor: {
          axis: 'y', // 'x' or 'y'
          colors: {
            // from value: color hex
            0: 'red',
            4: 'yellow',
            20: 'green'
          }
        },
        // Can set gradient line
        borderColor: {
          axis: 'y', // 'x' or 'y'
          colors: {
            // from value: color hex
            0: 'red',
            4: 'yellow',
            20: 'green'
          }
        }
      }
    }]
  },
  options: {
    responsive: true,
    scales: {
      y: {
        ticks: {
          beginAtZero: true
        }
      }
    }
  },
  plugins: [gradient] // using "chartjs-plugin-gradient"
})
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-gradient#.js"></script>

<canvas id="myChart"></canvas>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I change the color of certain lines in chartjs / vue-chartjs?

How can I change the color based on my grouping value instead of fill value in ggplot in R?

How can I change the color of AlertDialog title and the color of the line under it

Chartjs change grid line color

How can I change the background color of a row based on the value using HTML, CSS and JavaScript?

How can I change the background color of a column based on the value of another column

How can i change the color per section in this line chart?

How can I change the color of this blue text on my command line?

How can I make the line color of a fitted function change with y?

How do I change the color of an infobox in shinydashboard based on a string, not a value?

How can I change the color in javascript depending of object value

How can I change the color of a progress bar value in HTML?

How can I change the color of a list of icons according to percentage value?

How can I change size and color of clicked value at DateCalender MUI

Angular: How to change color of chartjs?

ChartJS. Change axis line color

How can I change the view output based on a value?

Using TypeScript, how can I change interface based on the value of a property?

How can I change the switch display based on the value from the database

How can I change a column value based on length of element in a DataFrame

How can I change the value of an item in an array based on multiple conditions?

How to change line segment color based on label value in chart.js?

How to change barchart color based on frequency value

How to change color of text based on $value

How do I change the line color of the tensorboard?

How can I shade a portion of a ChartJS line grph=

ChartJS with ChartJS DataLabels: Change Color per Dataset for Value Labels

I used a for loop to draw different curves. But how can I change every line to a different color?

In Vim, how can I change the color of the StatusLine when I'm in Command Line mode?