Articles in this section
Category / Section

How to set the gradient color for the JavaScript Stacked Bar Charts?

3 mins read

Description

This article shows how to set the gradient color for the JavaScript Stacked Bar Charts.

Solution

A gradient color refers to a visual effect where colors smoothly transition from one hue to another, creating a gradient or spectrum of colors. This gradient color is filled in the Chart by using the fill property in the series of a chart. You can create a linear-gradient SVG and then set the ID of it to the fill property in the series.

Code Snippet

index.html

<svg style="height:0">
<defs>
  <linearGradient id="gradient-chart1" x1="0" x2="0" y1="0" y2="1">
    <stop offset="0" />
    <stop offset="1" />
  </linearGradient>
  <linearGradient id="gradient-chart2" x1="0" x2="0" y1="0" y2="1">
    <stop offset="0" />
    <stop offset="1" />
  </linearGradient>
  <linearGradient id="gradient-chart3" x1="0" x2="0" y1="0" y2="1">
    <stop offset="0" />
    <stop offset="1" />
  </linearGradient>
</defs>
</svg>
<style>
    #gradient-chart1 stop {
          stop-color: green;
    }
    #gradient-chart1 stop[offset="0"] {
          stop-opacity: 0.75;
    }
    #gradient-chart1 stop[offset="1"] {
          stop-opacity: 0;
    }
    #gradient-chart2 stop {
          stop-color: orange;
    }
    #gradient-chart2 stop[offset="0"] {
          stop-opacity: 0.75;
    }
    #gradient-chart2 stop[offset="1"] {
          stop-opacity: 0;
    }
    #gradient-chart3 stop {
          stop-color: red;
    }
    #gradient-chart3 stop[offset="0"] {
          stop-opacity: 0.75;
    }
    #gradient-chart3 stop[offset="1"] {
          stop-opacity: 0;
    }
</style>

index.ts

let chart: Chart = new Chart({
.....
series: [
   {
       //Series type as 100% stacked bar
       type: 'StackingBar100',
       name: 'Apple',
       dataSource: chartData, xName: 'x', yName: 'y',
       fill:'url(#gradient-chart1)'
    }, {
       type: 'StackingBar100', name: 'Orange',
       dataSource: chartData, xName: 'x', yName: 'y1',
       fill:'url(#gradient-chart2)'
    }, {
       type: 'StackingBar100', name: 'Wastage',
       dataSource: chartData, xName: 'x', yName: 'y2',
       fill:'url(#gradient-chart3)'
    }
]
});
chart.appendTo('#container');

The following image illustrates the output of the above code.

image.png

View Sample in Stackblitz

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied