1
votes

I am adding chartjs in my application & want to change particular point background color based on condition at runtime. I am able to plot the chart correctly but don't know how to change plot color.

From chartjs document I understand we can do it using pointBackgroundColor but all example online is with design time example.

I tried with this._chart.chart.data.datasets[0].pointBackgroundColor = "red"; but its changed to all points and not to particular points

enter image description here

My version :
Angular ver 6
chartjs ver 2.7.3
ng2-charts 1.6.0

Component.ts code

@ViewChild(BaseChartDirective) public _chart: BaseChartDirective;

constructor(private router: Router, private _realtimeData  : RealtimeDataService) { 
 this._realtimeData.getRealtimeData(1)).subscribe(data => 
{
for (let stat of data) 
{
    this.labels.push(newDate(stat.DateTime).toLocaleDateString('de-IN', this.options));

    this.datasets_lines[0].data.push(stat.value);
    this.datasets_lines[1].data.push(stat.value1);
    this.datasets_lines[2].data.push(stat.vlue2);

    if ((stat.value > stat.value1) || (stat.value< stat.vlue2))
    {
    this._chart.chart.data.datasets[0].pointBorderColor = "red";
    }
    else
    {
    this._chart.chart.data.datasets[0].pointBorderColor = "black";
    } 

    this._chart.chart.update();
}
}
}

public chartColors: Array<any> = [
  { // first color
    borderColor: "#36ff2f",
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',
  },

  { // first color
    borderColor: '#1780cc',
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',

  },

  { // second color
    borderColor: '#ed8b00',
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',
  }];

HTML Code

<canvas 
      #mylinechart
      baseChart
      [chartType]="'line'"
      [datasets]="datasets_lines"
      [labels]="labels"
      [options]="chartOptions"
      [legend]="true"
      [colors]="chartColors"
  </canvas>
1

1 Answers

1
votes

I think you can directly change in this variable chartColors and you get output.

if (true)
{
  this.chartColors[0].pointBorderColor = "red";
}