[Chartjs]-Javascript – ChartJS Trying to change the borderColor and the fill color for negative numbers

1👍

Out of the Box you won’t be able to do this, the best would be something like in the example below (using the segementation styling, and a linear color gradient).

If you really need this exact look, you could check if someone has created a plugin, or create your own plugin (or inline plugin), that would override the normal rendering. (link to plugin documentation).

Here a demo, how I would do this:
(based on the configuration, you posted)

const lineChartData = {
    labels: [
      '01/22',
      '02/22',
      '03/22',
      '04/22',
      '05/22',
      '06/22',
      '07/22',
      '08/22',
    ],
    datasets: [
      {
        label: 'Profit',
        data: [2.4, 2.6, 2.23, 1.2, -2.2, -3.6, -1, 0.2],
        borderColor: '#0B9564',
        pointBackgroundColor: 'transparent',
        pointBorderColor: 'transparent',
        borderJoinStyle: 'bevel',
        fill: {
            value: -25,
            above: 'rgba(11, 149, 100, 0.08)'
        },
        segment: {
            borderColor: ctx => segmentColor(ctx, '#0B9564', 'red')
        }
      },
    ],
  };
  
function segmentColor(ctx, color1, color2){
    if(ctx.p0.parsed.y < 0 && ctx.p1.parsed.y < 0 ) {
        return color2;
    } else if (ctx.p0.parsed.y < 0){
        var gradient = myChart.ctx.createLinearGradient(ctx.p0.x, ctx.p0.y, ctx.p1.x, ctx.p1.y);
        gradient.addColorStop(.5, color2);
        gradient.addColorStop(1, color1);  
        return gradient
    } else if (ctx.p1.parsed.y < 0){
        var gradient = myChart.ctx.createLinearGradient(ctx.p1.x, ctx.p1.y, ctx.p0.x, ctx.p0.y);
        gradient.addColorStop(.5, color2);
        gradient.addColorStop(1, color1);   
        return gradient
    }
    return color1
}

const config = {
    type: 'line',
    data: lineChartData,
    options: {
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'right',
                labels: {
                    usePointStyle: true,
                },
            }
        },
    }
};

var myChart = new Chart(
    document.getElementById('chart'),
    config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>  

<div class="chart" style="height:184px; width:350px;">
    <canvas  id="chart" ></canvas>
</div>

Leave a comment