ng2charts using borderColor with array value

Viewed 141

I am trying to draw a line chart with individual colors per data entry. Using borderColor as an array of colors should have achieved desired behaviour but doesn't seem to work.

Did anyone else encounter this problem? Are there any easy workarounds?

Code used:

 public lineChartData: ChartDataSets[] = [
    { data: [65, 59, 80, 81], label: 'Series A' },
  ];
  public lineChartLabels: Label[] = ['January', 'February', 'March', 'April'];
  public lineChartOptions: (ChartOptions & { annotation: any }) = {
    responsive: true,
  };
  public lineChartColors: Color[] = [
    {
      borderColor: ['red', 'red', 'blue', 'blue'],
      backgroundColor: 'rgba(0, 0, 0, 0)',
    },
  ];
  public lineChartLegend = true;
  public lineChartType = 'line';

Output: Broken chart

1 Answers

If I correctly understand your question, you want to have different line colors between the data points. This can be done by extending an existing line chart as shown in this StackBlitz. Note that this approach doesn't use ng2-charts.

A simpler and probably better suited solution would be to use the Plugin Core API afterLayout hook. In there, you can create a linear gradient through CanvasRenderingContext2D.createLinearGradient().

lineChartPlugins = [{
  afterLayout: chart => {
    var ctx = chart.chart.ctx;
    var xAxis = chart.scales['x-axis-0'];
    var gradientStroke = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
    var dataset = chart.data.datasets[0];
    dataset.colors.forEach((c, i) => {
      var stop = 1 / (dataset.colors.length - 1) * i;
      gradientStroke.addColorStop(stop, dataset.colors[i]);
    });
    dataset.backgroundColor = gradientStroke;
    dataset.borderColor = gradientStroke;
    dataset.pointBorderColor = gradientStroke;
    dataset.pointBackgroundColor = gradientStroke;
    dataset.pointHoverBorderColor = gradientStroke;
    dataset.pointHoverBackgroundColor = gradientStroke;
  }
}];

Please have a look at the following StackBlitz.

StackBlitz shows an example that doesn't use ng2-charts.

Related