Chartjs-How can I change the color of a line chart segment in chart.js 2 depending on if it is a positive or negative slope?

0👍

The Chart.js documentation has an example showing what you want done using segments.

The key there is the segment definition (simplified to get rid of the skipped modifier to focus on the down modifier):

segment: {
  borderColor: ctx => down(ctx, 'rgb(192,75,75)'),
},

and its corresponding helper:

const down = (ctx, value) => ctx.p0.parsed.y > ctx.p1.parsed.y ? value : undefined;

So what does this do? For each segment [p0, p1] in your dataset, the down helper is called. If p0 > p1 (i.e. segment is sloping down), then the helper will return a color value (which is hard set to rgb(192,75,75) in the code) and affect it to the borderColor attribute for this segment.

Otherwise the helper function will return undefined and the segment (which is sloping up) will default to its default configuration (which, in the example linked above, is borderColor: 'rgb(75, 192, 192)').

In order to put all of this together in Svelte, all we need to do is declare a canvas element to hold our chart, get a reference to it with bind:this, and create the chart within onMount() to make sure the canvas has been mounted and its reference is available:

<script>
    import { onMount } from 'svelte';
    import Chart from 'chart.js/auto';
    let canvas;
    
    const down = (ctx, value) => ctx.p0.parsed.y > ctx.p1.parsed.y ? value : undefined;

    const genericOptions = {
        fill: false,
        interaction: {
            intersect: false
        },
        radius: 0,
    };

    const config = {
        type: 'line',
        data: {
            labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
            datasets: [{
                label: 'Price chart',
                data: [65, 59, 40, 48, 56, 57, 40],
                borderColor: 'rgb(75, 192, 192)',
                segment: {
                    borderColor: ctx => down(ctx, 'rgb(192,75,75)'),
                },
            }]
        },
        options: genericOptions
    };
    
    onMount(() => {
        const chart = new Chart(canvas, config);
    });
</script>

<div style="width: 800px;">
    <canvas bind:this={canvas}></canvas>
</div>

Demo REPL

Leave a comment