Abhijeet Rathore
Posted on March 25, 2020
This is part 2 of a 4 part series regarding how to create charts in Ionic 4 apps. In this Part 2, you’ll learn how to create various types of Charts using D3.js in Ionic 4 apps and PWA
(Part 1 — Adding Charts in Ionic 4 apps and PWA — Using Chart.js)
(Part 3— Adding Charts in Ionic 4 apps and PWA — Using HighCharts)
(Part 4 — Adding Charts in Ionic 4 apps and PWA : Part 4 — Using Google Charts)
In these posts, you’ll learn how to add and play with different types of charts in Ionic 4 apps. We will explore several alternatives for Charting i.e. Chart.js, D3.js, Highcharts, GoogleCharts and others.
Complete source code of this tutorial is available here — Ionic-4-d3js
What is Ionic 4
I know most of the readers reading this blog will know what is Ionic 4, but just for the sake of beginners, I explain this in every blog.
Ionic is a complete open-source SDK for hybrid mobile app development. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices.
In other words — If you create native apps in Android, you code in Java. If you create native apps in iOS, you code in Obj-C or Swift. Both of these are powerful, but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS. I’m a huge fan of Ionic and been developing Ionic apps for last 4 years.
What is d3.js
D3.js — D3.js (or just D3 for Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. It makes use of the Scalable Vector Graphics (SVG), HTML5, and CSS standards (but it can also work via canvas
too if need be). It is mainly used for real-time data visualizations or admin dashboards.
D3 creates amazingly detailed visualizations, both static and dynamic. One of the popular uses of D3.js is to visualization data over maps of different types
Here is another one — mapping Bible contradictions, available at http://bibviz.com
D3 can do magic if you know what you exactly want it to do. Check out more D3.js examples here
Some salient points for D3.js
- D3.js focuses on binding data to DOM elements.
- D3.js is written in JavaScript and uses a functional style. That means you can reuse code and add specific functions as you wish, which makes it powerful
- It is customizable ground up i.e. there is no standard bar-chart function, or pie-chart function you can use to create a simple chart. Everything needs to be made custom. This makes it amazingly powerful, but there is definitely a learning curve
- Because there is nothing pre-built, if you are simply looking for bar-charts and pie charts, D3 is probably not for you. But if you want your user to interact with data in a cool way, D3 is the answer
If you are looking for simpler chart solutions, there are many other popular charting libraries like Chart.js, HighCharts, FusionCharts, Angular Google Charts and more. All of these are custom libraries to create charts in a simple manner.
Structure of the post
We’ll go about the post in a step-by-step manner
- Create a basic Ionic 4 app
- Add D3.js to the app
- Create your first basic Bar Chart with D3.js — understand concepts
- Create simple Pie Chart with D3.js
- Create more advanced charts
- Test your app on Android
Complete source code of this tutorial is available here — Ionic-4-d3js
Step 1 — Create a basic Ionic 4 app
I have covered this topic in detail in this blog.
In short, the steps you need to take here are
- Make sure you have node installed in the system (V10.15.3 at the time of this blog post)
- Install ionic cli using npm (my Ionic version is 4.12.0 currently)
- Create an Ionic app using
ionic start
You can create a sidemenu
starter for the sake of this tutorial. On running ionic start ionic-4-d3js sidemenu
, node modules will be installed. Once the installation is done, run your app on browser using
$ ionic serve
The app will launch on browser. You can go to Inspect → Device Mode to see the code in a mobile layout. Next we’ll add the D3js library to our app.
Step 2 — Add D3.js to the app
To create charts/visualizations you need to add D3.js library to the app. Add the library from npm package
npm install d3 --save
This will install the library in your node modules. Now you can import different modules of the library in your page using import
syntax. We’ll see individual imports in next section.
That’s it ! You are ready to use D3.js in your app and PWA pages.
Step 3 — Create basic Bar chart with D3.js
D3.js uses HTML5 / CSS and SVGs to create charts and visualizations in HTML5. We will add a simple 1 div
in the HTML page of our app’s page, and access that div
in the page.ts
file to include our SVG based chart
Let’s add a simple div
element in HTML called barChart
Next we’ll import D3 and relevant modules in bar.page.ts
page. Here we’ll also access the barChart
div and create svg, axes inside it, and finally plot data inside it using D3 methods. Complete code to create a bar chart would be
You probably already realize that D3 is way more difficult for easier charts, compared to other libraries like Chart.js etc. There’s a lot happening in the code above, so let’s break it down
- First we imported D3 and its modules in the
bar.page.ts
using
import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Array from 'd3-array';
import * as d3Axis from 'd3-axis';
The module names are more or less self explanatory
2. There are four methods at work in this code
- this.init();
- this.initAxes();
- this.drawAxes();
- this.drawChart();
init()
This is the first method called after page loads. It selects barChart
element in the DOM and appends an svg
element to it. After that, all the lines are related to adding attributes to the svg
element, like height
, width
etc.
In the end, it also appends a <g>
element in the svg
. The <g>
SVG element is a container used to group other SVG elements. Transformations applied to the <g>
element are performed on its child elements, and its attributes are inherited by its children. It can also group multiple elements to be referenced later with the <use> element.
You can also check these element in the DOM using Chrome inspect tool. The svg
and <g>
elements are clearly visible here
initAxes()
In this function, we are initializing the axes of the chart. Notice how we have a scaleBand
function for X axis, but scaleLinear
for Y-axis. This is because we are creating a bar-chart (vertical), where the Y values will increase continuously, but X values are bundled for data. Also, the padding(0.1)
is given in X-axis to create a gap between the bars.
The domain (range) of the axes is also defined in a slightly different manner. X-axis has domain values as array, while Y-axis has domain values ranging from 0 to maximum of Y values.
drawAxes()
This function draws the initialized axes on the chart.
Notice, we have added two <g>
elements to the first <g>
element which we added in init() function. Next steps are adding different HTML attributes to the <g>
element.
Notice the call(d3Axis.axisBottom())
and call(d3Axis.axisLeft())
function calls. These are D3 specific function calls to create the axis values and text labels as per the data and domain defined in earlier steps.
At this point the chart looks like this
drawChart()
Finally, we draw the values on chart in this function.
We attach rect
element to every data contained in this.barData
and set attributes of the rect
(width, height, fill etc). Notice, the values are drawn as per the definition of this.x
and this.y
as defined in initAxes()
Here, you can attach custom classes, give each bar a different color and much more. There is no end of customization in D3 😎
The Bar chart will look like this. Pretty cool, right !
Step 4— Create basic Pie chart with D3.js
Pie chart creation is a little different from Bar Charts, because the linear domain is now changed to radial (angular?) domain. So instead of lengths we use arcs etc. Also, we’ll need to import different modules from D3.
Create a div
element with id pieChar
in your HTML. Then the complete TS code for a sample Pie chart will look like following
Notice that axes are replaced by labelArc
. Broadly the creation process remain similar. I will leave it you to understand some of the things going on here. Trust me, it’s very easy to understand.
The Pie chart will look this
You’ll probably notice that D3 charts, as I have shown above, do not look as attractive as other libraries. That is not entirely true. D3 charts can be customized to any level, and they can look exactly as any other library’s charts (or better), but that will take effort on your side.
PWA users ! Here’s how to current charts will look in a full screen desktop browser (remember, you can always customize the height, width and appearance as per screen size)
Step 5 — Create more advanced charts
As I discussed above, D3 can create amazing visualizations using JS. Let’s try to create something cool, which other libraries cannot build. I’m going to pick an example from the endless list of examples available at https://github.com/d3/d3/wiki/Gallery
This example is taken from http://www.redotheweb.com/CodeFlower/. This experiment visualizes source repositories using an interactive tree. Each disc represents a file, with a radius proportional to the number of lines of code (loc). All rendering is done client-side, in JavaScript. Try hovering on nodes to see the loc number, clicking on directory nodes to fold them, dragging nodes to rearrange the layout, and changing project to see different tree structures. Built with d3.js. Inspired by Code Swarm and Gource.
Step 6— Test your app in Android and as PWA
We have already tested the above d3 charts in browser. If you have carried out the above steps correctly, Android build should be a breeze.
Run the following command to create Android platform
$ ionic cordova platform add android
Once platform is added, run the app on device (Make sure you have a device attached to the system).
$ ionic cordova run android
Once your app is up and running on the device, you can start testing all the functions.
Conclusion
In this post we learnt how to create simple charts using D3.js in Ionic 4 apps and PWA. Since D3.js is amazingly customizable, you need to take a little more effort to create simple charts, compared to other libraries, but you can create some amazing stuff in D3.js which other libraries cannot even think of.
In next posts of this series, we’ll learn how to create charts in Ionic 4 using Highcharts, Angular Google charts and other libraries.
Complete source code of this tutorial is available here — Ionic-4-d3js
Checkout other posts in this series
(Part 1 — Adding Charts in Ionic 4 apps and PWA — Using Chart.js)
(Part 3 — Adding Charts in Ionic 4 apps and PWA — Using HighCharts)
(Part 4 — Adding Charts in Ionic 4 apps and PWA : Part 4 — Using Google Charts)
— — — — — — — — — — — — — — — — — — — — — — — — — — -
Buy “Ionic 4 Chart App Starter — Ion Chart” today!!
Ionic 4 Chart App Starter — Ion ChartCreate your own Dashboard app with this beautiful Ionic 4 chart app starter. Integrate your app with any back-end and…store.enappd.com
— — — — — — — — — — — — — — — — — — — — — — — — — —
Next Steps
Now that you have learned the implementation of D3.js for charting in Ionic 4, you can also try
- Ionic 4 PayPal payment integration — for Apps and PWA
- Ionic 4 Stripe payment integration — for Apps and PWA
- Ionic 4 Apple Pay integration
- Twitter login in Ionic 4 with Firebase
- Facebook login in Ionic 4 with Firebase
- Geolocation in Ionic 4
- QR Code and scanners in Ionic 4 and
- Translations in Ionic 4
If you need a base to start your next Ionic 4 app, you can make your next awesome app using Ionic 4 Full App
Posted on March 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.