Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to add Ionic charts and graph in Ionic

chartjs 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 of 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 Ionic chart we can use

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 covered 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, that is simple, clean, and engaging in 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 canvases that have to define explicit width and height.

Here is a screenshot of what we are building.

ionic charts example or ionic chart

Setting up and configure the project for Ionic charts from Chartjs

With the release of ionic version 4, the Ionic framework is no longer limited to angular. We can create ionic projects in different front-end frameworks like Angular, Vue, and React. Let’s 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

Let’s add three different canvas elements for each of our chartjs examples. We have three ionic-card and canvas objects. We have explicitly defined the height and width of our chart in our canvas. We can easily control our ionic size and we’ll discuss it later. Edit the home.page.html file to include three chart examples 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 the home.page.ts file, we need to import ViewChild, ElementRef from an 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 the @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 specified Ionic chart size directly in our canvas. Is best practice to remove the inline style and put it separately in our scss file. We can’t add style on the canvas element with id and class name. We can control Ionic chart size by controlling the width and height of the canvas container. Let’s add a container to 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 a div container with id=bar-chart-container over our barChart canvas. Now we can add different widths and heights to our bar chart by controlling the size of the canvas container. Edit scss file and add the following code.

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

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

Ionic chart double line example

In the previous example, we have a single line chart, we can include multiple line charts for comparison. In the example below let’s edit the home.page.ts file to include two lines of the chart in a single canvas. This is just a demo comparison of the social networking platforms. Here is a screenshot of what we are building.

ionic double line chart

We can apply different colors for each line indicating data on a particular entity. Let’s edit our home.page.ts file to include two-line data for our charts 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 a viewChild reference. Edit home.page.html files and add the 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 libraries and you can explore more depth in the official documentation.

Related posts

How to add Ionic charts and graph in Ionic

Leave a Reply

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

Scroll to top