Adding Charts to an Ionic Application

Reading Time: 4 minutes

Sometimes we need to create charts for displaying any progress or report in our Ionic mobile apps. Right now, we have to show you a simple step by step on creating beautiful charts (line, doughnut, and bar) easily using Ionic.

This Ionic 4 Chart App Starter is made for beginners and expert developers who want to integrate Charts in their Ionic 4 apps. Now you can start your own Dashboard app using charts app starter and it’s functionalities. This is a great starting point for app development, as more than half the work is done here. 

Chart.js makes it insanely easy to add charts to your Ionic applications. It’s a Javascript library that uses the HTML5 mobile application. The charts are super simple to set up, they look beautiful, and they are responsive by default – so they easily scale with your application as you change between devices or screen orientation.

This is going to be a very quick tutorial that will run through setting up Chart.js in an Ionic/Angular application and creating a few different types of graphs. Here’s what it will look like when we’re done:

Doughnut Responsive Chart

1. Install Chart.js

I will assume that you already have an Ionic project created that you want to set up Charts in – we will be walking through an example of adding charts to the “home” page, but you can add the charts wherever you like.

To begin, we are going to install the Chart.js library using npm. Just run the following command:

npm install chart.js --save

2. Set up the Template

As I mentioned before, Chart.js uses an HTML5 canvas element to display the Charts, so we will need to set that up in our template first.

Modify src/pages/home/home.html to reflect the following:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Charts
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    <ion-card>
      <ion-card-header>
        Bar Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #barCanvas></canvas>
      </ion-card-content>
    </ion-card>

    <ion-card>
      <ion-card-header>
        Doughnut Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #doughnutCanvas></canvas>
      </ion-card-content>
    </ion-card>

    <ion-card>
      <ion-card-header>
        Line Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #lineCanvas></canvas>
      </ion-card-content>
    </ion-card>
  </div>
</ion-content>

This is a pretty standard card layout, and we are using three cards to store three different charts. In each of these cards, we have a <canvas> element, and we add a local variable like #barCanvas so that we can easily grab a reference to it from our TypeScript file (which we will do very shortly).

3. Create the Responsive Charts

Now, all we need to do is generate the graphs. I’m going to use some sample code from the documentation to set up three graph examples, if you would like to know what other options are available you can take a look at the documentation.

Modify src/pages/home/home.ts to reflect the following:

import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
import { Chart } from "chart.js";

@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"]
})
export class HomePage implements OnInit {
  @ViewChild("barCanvas") barCanvas: ElementRef;
  @ViewChild("doughnutCanvas") doughnutCanvas: ElementRef;
  @ViewChild("lineCanvas") lineCanvas: ElementRef;

  private barChart: Chart;
  private doughnutChart: Chart;
  private lineChart: Chart;

  constructor() {}

  ngOnInit() {
    this.barChart = new Chart(this.barCanvas.nativeElement, {
      type: "bar",
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [
          {
            label: "# of Votes",
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
              "rgba(255, 99, 132, 0.2)",
              "rgba(54, 162, 235, 0.2)",
              "rgba(255, 206, 86, 0.2)",
              "rgba(75, 192, 192, 0.2)",
              "rgba(153, 102, 255, 0.2)",
              "rgba(255, 159, 64, 0.2)"
            ],
            borderColor: [
              "rgba(255,99,132,1)",
              "rgba(54, 162, 235, 1)",
              "rgba(255, 206, 86, 1)",
              "rgba(75, 192, 192, 1)",
              "rgba(153, 102, 255, 1)",
              "rgba(255, 159, 64, 1)"
            ],
            borderWidth: 1
          }
        ]
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true
              }
            }
          ]
        }
      }
    });

    this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
      type: "doughnut",
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [
          {
            label: "# of Votes",
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
              "rgba(255, 99, 132, 0.2)",
              "rgba(54, 162, 235, 0.2)",
              "rgba(255, 206, 86, 0.2)",
              "rgba(75, 192, 192, 0.2)",
              "rgba(153, 102, 255, 0.2)",
              "rgba(255, 159, 64, 0.2)"
            ],
            hoverBackgroundColor: ["#FF6384", "#36A2EB", "#FFCE56", "#FF6384", "#36A2EB", "#FFCE56"]
          }
        ]
      }
    });

    this.lineChart = new Chart(this.lineCanvas.nativeElement, {
      type: "line",
      data: {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
          {
            label: "My First dataset",
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: "butt",
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: "miter",
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: [65, 59, 80, 81, 56, 55, 40],
            spanGaps: false
          }
        ]
      }
    });
  }
}

Now we have added a doughnut chart and a line chart. These both use exactly the same method as we used for the bar chart, except that we supply a different configuration in the object that we supply.

Conclusion

Choosing between native and cross-platform development can be tricky. With applications that require high performance, native applications always win, since they can be designed to use the resources of the device entirely, while hybrid apps are not optimized for one platform directly.

At the start of the project, the developers need to consider priorities and the chances of future features and changes and make a big decision based on them.