I am using canvas to create bar charts. I created a static chart but I need a dynamic chart. I need to fetch the data from the backend using web API.
-
Here we like to see the code. Can you provide a minimal running sample? Please also take a momant to read this guide "How to ask a good question" here : stackoverflow.com/help/how-to-askGuillaume Raymond– Guillaume Raymond2020-01-08 07:14:13 +00:00Commented Jan 8, 2020 at 7:14
Add a comment
|
1 Answer
this is for line chart and pie chart
<canvas baseChart [datasets]="lineChartData"
[labels]="lineChartLabels" [options]="lineChartOptions"
[colors]="lineChartColors" [legend]="lineChartLegend"
[chartType]="lineChartType" [plugins]="lineChartPlugins">
</canvas>
<canvas baseChart [data]="pieChartData" [labels]="pieChartLabels"
[chartType]="pieChartType" [options]="pieChartOptions"
[plugins]="pieChartPlugins" [legend]="pieChartLegend"
(chartClick)="chartClicked($event)">
</canvas>
.ts file
///line chart
public lineChartData: ChartDataSets[] = []
public lineChartLabels: Label[];
public lineChartOptions: ( ChartOptions ) = { responsive: true, };
public lineChartColors: Color[] = [
{
borderColor: 'black',
backgroundColor: 'rgba(255,0,0,0.3)',
},
];
public lineChartLegend = true;
public lineChartType = 'line';
public lineChartPlugins = [];
///pie chart
public pieChartOptions: ChartOptions = {
responsive: true,
};
public pieChartLabels: Label[]// = [['Download Sales'], ['In Store Sales'], 'Mail Sales'];
public pieChartData: SingleDataSet// = [300, 500, 100];
public pieChartType: ChartType = 'pie';
public pieChartLegend = false;
public pieChartPlugins = [];
chartJson = {}
in ngoninit you can call
this.http.get( 'getGraphJSON' ).subscribe(( data ) => {
this.chartflag = true
this.lineChartData.push( data["linechartData"] );
this.lineChartLabels = data["lineChartLabels"];
this.pieChartLabels = data["pieChartLabels"];
this.pieChartData = data["pieChartData"];
} )
JSON:
{"pieChartLabels":["Nursing ","333999-Machinery Manufacturing","-Nursing Facilities","Social ","Electronic Product ","srvices","Social ","Professional, Scientific, and Technical Services","Repair and Maintenance","Transportation Equipment Manufacturing","Professional, Scientific, and Technical Services","Computer and Electronic Product Manufacturing","Crop Production","Publishing Industries (except Internet)","Machinery Manufacturing","Construction of Buildings"],"pieChartData":[83,57,42,41,37,33,33,33,12,12,9,9,4,3,3,3],"lineChartLabels":["Jun","Oct","Nov","Dec"],"linechartData":{"data":[1,2,5,423],"label":"Opportunity"}}