Marc
Marc

Reputation: 25

amCharts with gradient color for each bar

It is possible to make with amCharts a bar graph with gradient color of each bar, like this?

Upvotes: 1

Views: 1899

Answers (1)

notacouch
notacouch

Reputation: 3655

If you just want the gradient, please follow our guide on gradients. E.g.

var gradient = new am4core.LinearGradient();
gradient.addColor(am4core.color("red"));
gradient.addColor(am4core.color("blue"));
gradient.rotation = 90;
series.columns.template.fill = gradient;

gradient per column

However, if you want the gradients to be parallel, I'm afraid some custom coding is required.

We'll borrow some color utility and logic from v4 source. There's a helper function to figure out a color between two colors, via am4core.colors.interpolate, first 2 arguments are the min/max colors (as objects with r, g, and b), last is the percentage (as a decimal) of where between the 2 colors you're looking to pick a color out from.

With that we can use an adapter on columns' fill, e.g.:

var max = 500;
var red = am4core.color('red');
var blue = am4core.color('blue');
series.columns.template.adapter.add('fill', function(fill, column) {
  var columnGradient = new am4core.LinearGradient();
  columnGradient.rotation = 90;
  // interpolate(min.rgb, max.rgb, percent)
  console.log(am4core.colors.interpolate(blue.rgb, red.rgb, column.dataItem.dataContext.litres / max) );
  columnGradient.addColor(am4core.color( am4core.colors.interpolate(blue.rgb, red.rgb, column.dataItem.dataContext.litres / max) ), 1, 0);
  columnGradient.addColor("blue", 1, 1);
  return columnGradient;
});

parallel gradients

Demo:

https://codepen.io/team/amcharts/pen/f3a2f155bd88aba69621de6f88911f4b?editors=0010

Upvotes: 3

Related Questions