This is post 1 of a 4 part series regarding how to create charts in Ionic 4 apps.
(Part 2 — Adding Charts in Ionic 4 apps and PWA — Using D3.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.
In this Part 1, you’ll learn how to create various types of Charts using Chart.js
Complete source code of this tutorial is available here — Ionic-4-chartjs
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 Chart.js
Chart.js is a JavaScript library made for HTML5 that allows you to draw different types of charts. Chart.js uses canvas
to draw charts, so you have to include a polyfill to support older browsers. It has several amazing features:
- Chart.js supports a good number of popular chart types, as shown in the image below
2. Charts created by Chart.js are responsive, so they will adapt based on the space available. This makes if extremely friendly for Ionic 4 apps which can also be served as PWA.
3. Chart.js is the parent library for many other Charting libraries. It doesn’t have dependencies and is very small in size when minified and gzipped (around 10 Kb).
4. You also have the ability to include only the chart modules you want from Chart.js e.g. include only Bar chart module if you need only bar charts.
5. Chart.js has great documentation and good community support, so you can relax even if you are just starting on Chart.js. It’s not difficult at all, and any issue you face is probably already solved by someone.
There are some “cons” of Chart.js as well
- Limited to only 6 graph types, and lacks the flexibility offered by other options. For example, controlling the display of tooltips is fairly limited.
- It is Canvas based, so faces the same issues as non-vector formats.
Other Popular Javascript Charting libraries
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. It is mainly used for real-time data visualizations or admin dashboards.
Check out more D3.js examples here
There are many other popular charting libraries like 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 Chart.js to the app
- Create your first chart
- Create chart from external API call / JSON
- Test your app on Android
Complete source code of this tutorial is available here — Ionic-4-chartjs
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-chartjs 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 chart library to our app.
Step 2 — Add Chart.js to the app
To create charts you need to add Chart.js library to the app. Add the library from npm package
npm install charts.js --save
This will install the library in your node modules. Now you can import the library in your page using
import { Chart } from 'chart.js';
That’s it ! You are ready to use Chart.js in your app and PWA pages.
Step 3 — Create your first chart
Chart.js uses canvas
to create charts in HTML5. You will have to add a canvas
element in page HTML, and access this canvas
in page.ts
file to create chart on.
Let’s add a simple canvas
element in HTML
Vertical Bar Chart
Access #barChart
in home.page.ts
and create a simple vertical bar chart on the canvas
. The complete code of home.page.ts
will look like following
Note, @ViewChild(‘barChart’) barChart;
accesses the canvas
element in a variable barChart
. This is the element used later to draw on.
The Bar chart will look like this
Let’s go over some of the parameters and their usage
- type — Type defines the variety of chart e.g. line, bar, pie etc
- data — Data is the dataset which you are plotting on the charts.
- data → labels — To label a particular data set
- data → datasets — data object for one dataset. Multiple such objects can be plotted together
-
scales —
scales
contains options for X and Y axes, grid options, sizing etc.
Cool, right ? Now, let’s generate more awesome charts using various options.
Horizontal Bar Chart
To change the vertical chart to horizontal, you simply need to change type
from line
to horizontalLine
. The result will be this
Custom Height For Chart
As you can see in the previous screen, the horizontal chart appears very squished. We can adjust the bar thickness and overall height of the chart to change this.
By default, all the bars take equal spaces in the chart. We can set the chart height to a custom height using
createHrzBarChart2() {
let ctx = this.hrzBarChart2.nativeElement;
ctx.height = 400;
this.hrzBars2 = new Chart(ctx, {
....
This will set the height to 400, and the bars’ width will adjust automatically. You can set
options → scales → xAxes → barPercentage = 0.9
This will set the width of bars to 90% of the maximum possible. This creates a neat looking gap between the bars.
Custom Colors
Another cool thing is — you can set custom colors to each bar. You will have to set
data → datasets (element) → backgroundColor = color Array
The number of elements of this array should be same as number of data points, otherwise the missing elements will get a gray
color.
You can generate random colors using a function like following
Resulting chart will look like this with random colors
Grouped Bar Charts
For practical purposes, we often compares two datasets. This can be achieved by simply adding one more dataset in the data
element
Stacked Bar Charts
If you want to see a division of data into different colors with a stacked bar chart, you can simple add
options → scales → xAxes → stacked: true
This will create a stacked bar chart like following
Simple Line Chart
To create a simple line chart from the same dataset as the bar chart, just replace type:'bar’
with type:'line'
. You will get the following result (Keep the backgroundColor: rgba(0,0,0,0)
)
Simple Area Chart
If you provide a background color in a line chart, you’ll get an Area Chart
Grouped Line Chart
Adding multiple dataset, similar to the bar chart example, you can create grouped line charts as can be seen below.
Stacked Area Chart
In grouped line chart, if you add backgroud color to each dataset, you’ll get a stacked area chart.
Simple Pie Chart
To create a simple Pie chart replacetype:'line’
with type:'pie'
. If you have the background color set on the random color dataset as shown above, then it will look something like below.
Simple Doughnut Chart
To create a simple Pie chart replacetype:'pie’
with type:'doughnut'
. Make sure you have the background colors set on the random color dataset as shown above.
Step 4 — Create chart from external API call / JSON
To simulate a real app environment, we’ll fetch data from an API, and then create charts using the same. This will show the effects of incoming data delay etc.
To create a dummy API, we can use mocky.io
. Mocky helps to create dummy API with the response you want to send. It then gives you a URL which you can fetch when calling the API. You can use the following API URL
http://www.mocky.io/v2/5d28754a2c000066003eda63?mocky-delay=3000ms
The response will be
Now, to call API, we need to use HttpClient
in Ionic. Import HttpClientModule
in app.module.ts
import { HttpClientModule } from '@angular/common/http';
and add the same in imports as well
imports: [
...,
HttpClientModule,
...
],
...
Import HttpClient
in home.page.ts
and declare it in constructor as well. Now fetch data using a simple function
I have also added a 3000ms delay to simulate server delays. The data received is supplied to the chart creation function. The result look something like this
Step 5 — Test your app in Android and as PWA
Now that everything is ready, we need to build this app for Android. 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.
In browser (As PWA), the charts will appear a little bigger 😄
Conclusion
In this post we learnt how to create various charts using Chart.js in Ionic 4 apps and PWA. Since Chart.js is amazingly light and has great documentation, it is developers’ first choice when it comes to creating charts.
In next posts of this series, we’ll learn how to create charts in Ionic 4 using D3, Highcharts and other libraries.
Complete source code of this tutorial is available here — Ionic-4-chartjs
Check out other posts in this series
(Part 2 — Adding Charts in Ionic 4 apps and PWA — Using D3.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)
Next Steps
Now that you have learned the implementation of charts using chart.js 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
Top comments (0)