The D3 has become a standard for data visualization. We have a lot of libraries for adding charts in Ionic. We can use Chart.js and angular2-highcharts. The Chart.js is easy to use and allow us to build chart quickly as compared to D3. The D3 has a more learning curve as compared to other chart libraries. The D3 allows us to create more complex and provide more flexibility in creating data visualization on the web.
In this example, we will test simple example how to integrate D3 chart in Ionic 3. Follow the following step
Step 1: Create and configure the D3 Ionic apps
With D3 version 4 is a collection of the modules and we can use each module independently, with minimum dependency. In this example, we are using the D3 whole module.
Add two more page to our apps
Step 2: Set up the Tabs Template
We don’t need to test this app on real device, we can test on the browser. First, we modify the existing code of the tab.html. Replace existing code with the following code in pages/tabs/tabs.html
Here we are using SuperTabsModule of ionic 2 and we have to import this module in app/app.module.its file. In the app/app.module.ts we also have to import BarChartPage and PieChartPage. Add the following code in app/app.module.ts file
Modify the pages/tabs/tabs with following code.
Step 3: Set up the Char Template
The D3 uses an SVG element of HTML to display graphic on the web. We will be creating two different charts in two pages. First, we need to set up the data on which D3 is generating the chart. Create a new folder called data and add data.ts a file in the data folder. Add the following data in src/data/data.ts file
Modify the pages/bar-chart/bar-chart.html file
Modify the pages/pie-chart/pie-chart.html file
Step 4: Creating chart
Now we will generate the two chart, first, we will generate a bar chart. In the bar chart, we generate bar chart on the number of employees in popular IT company. This is just fake data, as for example, we are using it.
Modify the following code in src/pages/bar-chart/bar-chart.ts
As we know that D3 is collections of modules, we are importing some of the different module needed to generate bar chart in ionic.
Modify the following code in src/pages/pie-chart/pie-chart.ts
We can modify the data to change to generate different pie and bar chart and we can use same method to generate different graphic of D3 in ionic.