score:11
In standard chart.js you can use the .update()
prototype method to re-render a chart after you have modified its data (including labels).
However, it appears that ng2-charts doesn't provide a mechanism to trigger the update (as per this github issue). I'm not very experienced in Angular2 at all, but perhaps this will work for you? The approach was taken from a comment made by zbagley in the github issue posted 17 days ago (unfortunately I could not find a way to generate a url referencing this specific comment).
The approach is to basically not render your chart until the data is available. Here is the change to your component.ts code.
import { Component } from '@angular/core';
import { ChartsModule } from 'ng2-charts';
import { PredictionService } from './prediction.service'
@Component({
selector: 'prediction-result-chart',
templateUrl: './predictionResultChart.component.html'
})
export class PredictionResultChartComponent {
public pieChartLabels:string[] = [];
public pieChartData:number[] = [];
public pieChartType:string = 'pie';
public JSONobject = {};
public isDataAvailable:boolean = false;
constructor(private predictionService: PredictionService){
this.getPredictions();
}
public getPredictions() {
this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe();
}
public populateChart(obj): void {
let labels:string[] = [];
let data:number[] = [];
for (var i = 0; i < obj.predictions.length; i++)
{
labels.push(String(obj.predictions[i].class));
data.push(obj.predictions[i].percentage);
};
this.pieChartData = data;
this.pieChartLabels = labels;
this.isDataAvailable = true;
}
public chartClicked(e:any):void {}
public chartHovered(e:any):void {}
}
And then you would use ngIf
in your component.html code.
<div style="display: block" *ngIf="isDataAvailable">
<canvas baseChart
[data]="pieChartData"
[labels]="pieChartLabels"
[chartType]="pieChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
score:0
first you to be sure that the order of labels is matching the order of the data_set, so basicly you have these two variables :
private datasets_pie = [
{
label: "Commissions",
data: Array<any>(),
backgroundColor: Array<any>()
}
];
private labels_pie = Array<any>();
secondly i had the same issue with the colors, so i had to insert the colors manually, here is an example :
private chartColors: any[] = [{ backgroundColor: ["#FFA1B5", "#7B68EE", "#87CEFA", "#B22222", "#FFE29A", "#D2B48C", "#90EE90", "#FF69B4", "#EE82EE", "#6A5ACD", "#b8436d", "#9ACD32", "#00d9f9", "#800080", "#FF6347", "#DDA0DD", "#a4c73c", "#a4add3", "#008000", "#DAA520", "#00BFFF", "#2F4F4F", "#FF8C00", "#A9A9A9", "#FFB6C1", "#00FFFF", "#6495ED", "#7FFFD4", "#F0F8FF", "#7FFF00", "#008B8B", "#9932CC", "#E9967A", "#8FBC8F", "#483D8B", "#D3D3D3", "#ADD8E6"] }];
finally after creating these object properly, you have to call this function :
setTimeout(() => {
if (this.chart && this.chart.chart && this.chart.chart.config) {
this.chart.chart.config.data.labels = this.labels_pie;
this.chart.chart.config.data.datasets = this.datasets_pie;
this.chart.chart.config.data.colors = this.chartColors;
this.chart.chart.update();
}
this.sommeStat = this.getSomme();
});
so i think that this might work :
import { Component, ViewChild, ElementRef } from '@angular/core';
import { ChartsModule } from 'ng2-charts';
import { PredictionService } from './prediction.service';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';
@Component({
selector: 'prediction-result-chart',
templateUrl: './predictionResultChart.component.html'
})
export class PredictionResultChartComponent{
@ViewChild(BaseChartDirective) chart: BaseChartDirective;
public pieChartType: string = 'doughnut';
//public lineChartType: string = 'line';
private datasets_pie = [
{
label: "Commissions",
data: Array<any>(),
backgroundColor: Array<any>()
}
];
private labels_pie = Array<any>();
//private datasets_line : LineData[] = [];
// private datasets_line : { label : string, data : Array<any>}[] ;
// private labels_line = Array<any>();
private chartColors: any[] = [{ backgroundColor: ["#FFA1B5", "#7B68EE", "#87CEFA", "#B22222", "#FFE29A", "#D2B48C", "#90EE90", "#FF69B4", "#EE82EE", "#6A5ACD", "#b8436d", "#9ACD32", "#00d9f9", "#800080", "#FF6347", "#DDA0DD", "#a4c73c", "#a4add3", "#008000", "#DAA520", "#00BFFF", "#2F4F4F", "#FF8C00", "#A9A9A9", "#FFB6C1", "#00FFFF", "#6495ED", "#7FFFD4", "#F0F8FF", "#7FFF00", "#008B8B", "#9932CC", "#E9967A", "#8FBC8F", "#483D8B", "#D3D3D3", "#ADD8E6"] }];
private options = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
public JSONobject = {}
constructor(private predictionService: PredictionService){
this.getPredictions();
}
public getPredictions() {
this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe();
}
public populateChart(obj): void{
this.labels_pie = [];
this.datasets_pie[0]['data'] = [];
for (var i = 0; i < obj.predictions.length; i++)
{
labels.push(String(obj.predictions[i].class));
this.datasets_pie[0]['data'].push(obj.predictions[i].percentage);
};
let arrColors: any[];
arrColors = arrColorsCopy.splice(0, this.products.length);
this.datasets_pie[0]['backgroundColor'] = arrColors;
setTimeout(() => {
if (this.chart && this.chart.chart && this.chart.chart.config) {
this.chart.chart.config.data.labels = this.labels_pie;
this.chart.chart.config.data.datasets = this.datasets_pie;
this.chart.chart.config.data.colors = this.chartColors;
this.chart.chart.update();
}
});
}
public chartClicked(e:any):void {}
public chartHovered(e:any):void {}
}
for the html it should be looking like this :
<div class="col-md-8">
<div class="chart">
<canvas baseChart [datasets]="datasets_pie" [labels]="labels_pie" [chartType]="pieChartType" [colors]="chartColors"> </canvas>
</div>
</div>
thats all, you should try this way, it should work
score:1
I updated the chart labels by updating the labels in the config property.
import { Component } from '@angular/core';
import { ChartsModule } from 'ng2-charts';
import { PredictionService } from './prediction.service'
import { BaseChartDirective } from 'ng2-charts'; // ----- added
@Component({
selector: 'prediction-result-chart',
templateUrl: './predictionResultChart.component.html'
})
export class PredictionResultChartComponent {
public pieChartLabels:string[] = [];
public pieChartData:number[] = [];
public pieChartType:string = 'pie';
public JSONobject = {};
public isDataAvailable:boolean = false;
@ViewChild('mainChart') mainChart: BaseChartDirective; // ----- added
constructor(private predictionService: PredictionService){
this.getPredictions();
}
public getPredictions() {
this.predictionService.getPredictions('hello').do(result =>
this.populateChart(result)).subscribe();
}
public populateChart(obj): void {
let labels:string[] = [];
let data:number[] = [];
for (var i = 0; i < obj.predictions.length; i++)
{
labels.push(String(obj.predictions[i].class));
data.push(obj.predictions[i].percentage);
};
this.pieChartData = data;
this.mainChart.chart.config.data.labels = labels; // ---- updated
this.isDataAvailable = true;
}
public chartClicked(e:any):void {}
public chartHovered(e:any):void {}
}
In HTML add #{chartName} to access it
<div style="display: block" *ngIf="isDataAvailable">
<canvas #mainChart="base-chart" baseChart
[data]="pieChartData"
[labels]="pieChartLabels"
[chartType]="pieChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
score:2
I can get the values when i print to console but does not display on the chart.
this.pieChartLabels :: ['PayDirect agent deposit','GtCollections agent deposit','Quickteller agent deposit']
this.pieChartData :: [1990,1202,2476]
Is there a way to update the chart. It seems the chart was loaded before the data was received from the web service.
isDataAvailable2 = true
but the chart never loaded.
Source: stackoverflow.com
Related Query
- Angular2 Update ng2-charts with labels
- Angular2 charts (chart.js) Labels not vertical even though option is set
- Chart.js 2 line charts with separate dataset labels
- charts labels and data with php arrays
- Angular 8 and ng2 charts - Updating labels and data
- Chartjs charts drawing with the same colour after update
- ng2-charts update labels and data
- ChartJS New Lines '\n' in X axis Labels or Displaying More Information Around Chart or Tooltip with ChartJS V2
- Chart.js Line-Chart with different Labels for each Dataset
- Page with multiple chart.js charts to pdf
- How to drill down charts with ChartJS?
- ChartJS - Donut charts with multiple rings
- How to display Line Chart dataset point labels with Chart.js?
- How to add images as labels to Canvas Charts using chart.js
- How to fix bars in Chart.js with long labels
- Chart.js tooltips callback function with pie charts
- Chart.js - Draw bar chart with multiple labels
- Chart.js - Line charts with different colors for each border lines
- How to display data labels outside in pie chart with lines in ionic
- Line chart with large number of labels on X axis
- Chart.js - displaying multiple line charts using multiple labels
- How to display the labels in doughnut chart using ng2 charts?
- Chart.js Bubble chart with custome X-axis labels
- Add zoom event handler to charts for chartjs with chartjs-plugin-zoom
- Live Update Callback -> afterTitle with Array via JSON file
- chart.js v2: Align time scale labels with the center of the bars
- Multiple charts in one page with chart.js
- Chartsjs update datasets with dropdown
- Chart.js Multiple charts with one common legend
- Update charts in chartjs and angular
More Query from same tag
- HTML minification via Gulp.js is breaking my Chart.js chart in my Angular app
- Chart.js responsive css size
- Plot a multi-line graph from grouped JSON object using Charts.js
- Usage for angular-chart : colors and fonts
- Can I add a callback function to the legend while keeping the original functionality?
- Chartjs - Two Y-axis scale problems
- how I can get label name when user click on particular area in doughnut chart.js? I am not able to find the index of selected area for chart.js
- Chart.js Custom Image for Each Point
- ChartJS: Translate x axis month to other languages
- Change axes position in line chart
- create a chart.js point dataset from json
- Different color for line segments in ChartJS
- Move tooltip further from data point for Chart.js?
- Add Time Scaling to linechart (Chart.js)
- Chart.js - disable tooltip when cursor moves outside the main canvas
- Changing Legend Label Position in VueChartjs
- Uncaught ReferenceError: Chart is not defined in Laravel mix
- Vue.js chart not working?
- Chartjs2 set data 0 to type doughnut
- Why are some react-chartjs-2 options being ignored?
- How to fill remaining polar area with color
- Chart.js always visible labels
- chartjs plugin datalabels does not show value on charts
- Missing colors in my Chart.js, my data looks fine, but no color
- Animate datasets separately
- Is there any way to change the font color and size of labels in Chartjs 3.0.0
- How to remove paddings in Bar chart? (Chart.JS)
- Can I add some variables to my chart.js in page know that variables?
- How to determine chart type inside 'chart.js' pluginservice
- How to plot a line graph with x and y data