How to add Ionic charts and graph in Ionic

We have plenty of open sources and paid libraries to add Ionic charts and graphs to our project. Data visualization is an important aspect for modern applications, where we have used charts for data analysis and real live data.

In this article, we’ll explore different libraries to add ionic charts and graphs. We’ll also implement demo of the bar, doughnut and line charts using the popular chart.js library in our ionic applications.

Other popular javascript charting libraries.

We can add a chart into ionic apps from the different libraries, the most popular libraries for adding charts are  D3js, Chart.js, highcharts, and more. The Chart.js  are easy to add to the Ionic framework as compared to D3. We have already cover articles on other popular chart libraries in our ionic project charts.

What is Chart.js library

The chart.js  is an open-source Javascript library, is simple, clean, and engaging HTML5 based JavaScript charts. Chart.js is an easy way to include animated, interactive graphs on your website for free. Chart.js is for data visualization, which supports 8 chart types: bar, line, area, pie (doughnut), bubble, radar, polar, and scatter.

Examples of Ionic charts and graph from Chartjs library

We’ll demonstrate doughnut, bar, and a line chart of chartjs in an ionic application. In order to display the chart of Chart.js in ionic, we need a canvas element. We have 3 cards, each card has an element canvas element, and we add a local variable like so #barCanvas that we can easily grab a reference to it from our TypeScript file. We have three canvas have to define explicit width and height.

Here is screenshot of what we are building.

ionic charts example

Setting up and configure the project for Ionic charts from Chartjs

With the release of ionic version 4, the Ionic framework no longer limited to angular. We can create ionic projects in different front-end frameworks like Angular, Vue, and React. Let first create a blank Ionic Angular project for our ionic Ionic charts example and we also need to install the chartjs library in an ionic project. This can achieve by running the following command in the terminal.

ionic start chartjs blank --type=angular
cd chartjs
npm install chart.js --save

Set up the Ionic charts template

Lets add three different canvas element for each of our chartjs example. We have three ionic-card and canvas object. We have explicit define height and width of our chart in our canvas. We can easily control our ionic size and we’ll discuss it later. Edit home.page.html file to include three chart example in our template.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Charts.js in Ionic
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <div class="ion-padding">
    <ion-card>
      <ion-card-header>
        Bar Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #barCanvas style="position: relative; height:20vh; width:40vw"></canvas>
      </ion-card-content>
    </ion-card>

    <ion-card>
      <ion-card-header>
        Doughnut Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #doughnutCanvas style="position: relative; height:20vh; width:40vw"></canvas>
      </ion-card-content>
    </ion-card>
 
    <ion-card>
      <ion-card-header>
        Line Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #lineCanvas style="position: relative; height:20vh; width:40vw"></canvas>
      </ion-card-content>
    </ion-card>
  </div>
</ion-content>

In home.page.ts file we need to import ViewChild, ElementRef from angular core package and chart from chartjs library.

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

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

  barChart: any;
  doughnutChart: any;
  lineChart: any;

  constructor() { }

  ngAfterViewInit() {
    this.barChartMethod();
    this.doughnutChartMethod();
    this.lineChartMethod();
  }

  barChartMethod() {
    this.barChart = new Chart(this.barCanvas.nativeElement, {
      type: 'bar',
      data: {
        labels: ['BJP', 'INC', 'AAP', 'CPI', 'CPI-M', 'NCP'],
        datasets: [{
          label: '# of Votes',
          data: [200, 50, 30, 15, 20, 34],
          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
            }
          }]
        }
      }
    });
  }

  doughnutChartMethod() {
    this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
      type: 'doughnut',
      data: {
        labels: ['BJP', 'Congress', 'AAP', 'CPM', 'SP'],
        datasets: [{
          label: '# of Votes',
          data: [50, 29, 15, 10, 7],
          backgroundColor: [
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)'
          ],
          hoverBackgroundColor: [
            '#FFCE56',
            '#FF6384',
            '#36A2EB',
            '#FFCE56',
            '#FF6384'
          ]
        }]
      }
    });
  }

  lineChartMethod() {
    this.lineChart = new Chart(this.lineCanvas.nativeElement, {
      type: 'line',
      data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'November', 'December'],
        datasets: [
          {
            label: 'Sell per week',
            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, 10, 5, 50, 10, 15],
            spanGaps: false,
          }
        ]
      }
    });
  }
}

We need @ViewChild decorator to grab a reference to the local variable that we have attached to the canvas in the template, and then we supply that element to the new Chart when we are creating a chart. All we have to do is supply a Chart with an object that defines the type of chart we want, and the type of data we want to display.  When we try to call our chart method in ngOnInit it shows an error nativeElement of undefined and we need to call all chart methods in ngAfterViewInit() where @ViewChild and @ViewChildren will be resolved.

Ionic chart size: setting width and heigh

In our template we have specify Ionic chart size directly in our canvas. Is best practice to remove inline style and put separate in our scss file. We can’t add style on canvas element with id and class name. We can control Ionic chart size by controlling width and height of canvas container. Let add conatiner on our bar chart example and edit our template.

    <ion-card>
      <ion-card-header>
        Bar Chart
      </ion-card-header>
      <ion-card-content>
        <div id="bar-chart-container">
          <canvas #barCanvas></canvas>
        </div>
      </ion-card-content>
    </ion-card>

We have added div container with id=bar-chart-container over our barChart canvas. Now we can add different width and height on our bar chart by controlling the size of canvas container. Edit scss file and add following code.

#bar-chart-container {
  height: 200px; 
  width: 400px;
}

Now we can used media query or flex to control responsiveness of Ionic chart size.

Ionic chart double line example

In previous example we have single line chart, we can include multiple line chart for comparision. In example below let edit home.page.ts file to include two line of chart in single canvas. This is just demo comparision for social networking platform. Here is screenshot of what we are building.

ionic double line chart

We can apply different color for each line indicating data on particular entity. Let edit our home.page.ts file to include two line data for our chartjs line chart.

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  @ViewChild('doubleLineCanvas') doubleLineCanvas: ElementRef;

  doubleLineChart: any;

  constructor() { }

  ngAfterViewInit() {
    this.doubleLineChartMethod();
  }

  doubleLineChartMethod() {

    this.doubleLineChart = new Chart(this.doubleLineCanvas.nativeElement, {
      type: 'line',
      data: {
        labels: ["Facebook", "Instagram", "Mixed Technologies"],
        datasets: [
          {
            label: "Facebook",
            data: [150, 250, 145, 100],
            backgroundColor: "rgba(40,125,200,.5)",
            borderColor: "rgb(40,100,200)",
            fill: true,
            lineTension: 0,
            radius: 5
          },
          {
            label: "Instagram",
            data: [30, 90, 151, 220],
            backgroundColor: "rgba(240,78,71,.5)",
            borderColor: "rgb(240,78,71)",
            fill: true,
            lineTension: 0.2,
            radius: 5
          }
        ]
      },

      options: {
        responsive: true,
        title: {
          display: true,
          position: "top",
          text: "Facebook to Instagram - Social Networking",
          fontSize: 12,
          fontColor: "#666"
        },
        legend: {
          display: true,
          position: "bottom",
          labels: {
            fontColor: "#999",
            fontSize: 14
          }
        }
      }
    })
  }
}

We need to add canvas for our double line chart example and need to add viewChild reference. Edit home.page.html files and add following code.

    <ion-card>
      <ion-card-header>
        Double Line Chart
      </ion-card-header>
      <ion-card-content>
          <canvas #doubleLineCanvas style="position: relative; height:20vh; width:40vw">     
          </canvas>
      </ion-card-content>
    </ion-card>

Summary
We have explored how we can include charts and graphs in our ionic project. You can modify this code according to your choice and we have added this code to the GitHub repository. This was a small introduction to how we can use chartjs in our angular ionic project. Charts and D3js are amazing chart library and you can explore more depth in the official documentation.

Related posts

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top