How to Build Drill Down Chart in Angular?
Drill-down charts are widely used to show data in depth with additional information. Drill-down charts shows relation between parent-child data / chart. For example: A chart can show yearly sales data (2010, 2011, 2012,…) and once you click on any of the year, it shows monthly / quarterly data of that particular year. In this article, let me brief how to create drill-down chart in angular using CanvasJS angular chart.
Add CanvasJS directives to your project
- Download CanvasJS from this link.
- Add the angular chart component files to your project (canvasjs.min.js & canvasjs.angular.component.js).
- Register CanvasJS module
import { NgModule } from '@angular/core';
import * as CanvasJSAngularChart from '../assets/canvasjs.angular.component';
var CanvasJSChart = CanvasJSAngularChart.CanvasJSChart;
@NgModule({
declarations: [
AppComponent,
CanvasJSChart
],
})
export class AppModule { }
Refer CanvasJS Angular Integration section for more info / troubleshooting.
Structuring Drill-Down Data
CanvasJS accepts data in JSON format. That doesn’t mean you have to store data in JSON file always. It simply means data has to be parsed to JSON format before passing it to chart options. The data can either be read from JSON / XML / CSV files or from a local JavaScript variable.
To build drill-down chart, we need to have parent(yearly) & child(quarterly) data.
yearlyData: [{
cursor: 'pointer',
dataPoints: [
{
label: "2019",
y: 191630,
name: "2019",
color: '#f2c80f'
}, {
label: "2020",
y: 203770,
name: "2020",
color: '#fc625e'
}, {
label: "2021",
y: 193700,
name: "2021",
color: '#01b8aa'
}]
}],
drilldownData: {
'2019': [{
color: "#f2c80f",
dataPoints: [
{ label: 'Q1', y: 48980 },
{ label: 'Q2', y: 42690 },
{ label: 'Q3', y: 46980 },
{ label: 'Q4', y: 52980 }
]
}],
'2020': [{
color: '#fc625e',
dataPoints: [
{ label: 'Q1', y: 51780 },
{ label: 'Q2', y: 48590 },
{ label: 'Q3', y: 52500 },
{ label: 'Q4', y: 50900 }
]
}],
'2021': [{
color: '#01b8aa',
dataPoints: [
{ label: 'Q1', y: 42600 },
{ label: 'Q2', y: 44960 },
{ label: 'Q3', y: 46160 },
{ label: 'Q4', y: 48240 }
]
}]
}
Perform Drill Down on Click
Bind click event to datapoints. Update the chart data on clicking datapoint & re-render the chart.
drilldownHandler = (e: any) => {
this.chart.options = this.drilldownChartOptions;
this.chart.options.data = this.options.drilldown[e.dataPoint.name];
this.chart.options.title = { text: e.dataPoint.name };
this.chart.render();
};
Check working sample here: https://stackblitz.com/edit/angular-drilldown-chart
Subscribe to my newsletter
Read articles from Vishwas R directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by