Angular 11 Chart.js with ng2-charts Tutorial with Line, Bubble, Pie, Bar, Doughnut, Radar Examples

In this comprehensive Angular 11 Chart JS tutorial, we will learn how to create different charts to display data to users. Also, we will be using the ng2-charts JavaScript library to spruce up charts in Angular.

Chat.js is a robust but subtle JavaScript charting for web designers and developers. Whereas, ng2-charts is used to build beautiful charts for Angular2+ based application.

You say anything, and it satisfies every demand, whether it is customization, animation, or responsiveness. The ng2-charts library aligns with chart js; you can create almost 8 types of charts using its baseChart standard directive:

  1. Pie
  2. Bar
  3. Line
  4. Radar
  5. Polar Area
  6. Doughnut
  7. Bubble
  8. Scatter

Install Angular Application

Install a fresh Angular project using the Angular CLI. Ignore it if already installed.

ng new angular-chartjs-example

? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS

Create components in angular to display all the charts that we are going to build in a while.

ng generate component charts/bar-chart
ng generate component charts/bubble-chart
ng generate component charts/line-chart
ng generate component charts/pie-chart
ng generate component charts/radar-chart
ng generate component charts/doughnut-chart

Install/Set up ng2-charts module in Angular

The next step is important, so be attentive. Install the ng2-charts library in angular application, It also requires a dependency, so install the chart.js package also.

npm install --save ng2-charts
npm install --save chart.js

Next, Import the ChartsModule in the app.module.ts.

// app.module.ts
...
...
...
import { ChartsModule } from 'ng2-charts';

@NgModule({
  declarations: [
    AppComponent,
    ...
    ...
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ChartsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

We are almost ready to go ahead and check out the properties of ng2-chart to better create charts in angular.

You can create or customize charts with the following properties.

  • data (SingleOrMultiDataSet) – set of points of the chart, it should be MultiDataSet only for line, bar, radar and doughnut, otherwise SingleDataSet.
  • datasets ({ data: SingleDataSet, label: string }[]) – data see about, the label for the dataset which appears in the legend and tooltips.
  • labels (Label[]) – x-axis labels. It’s necessary for charts: line, bar, and radar. And just labels (on hover) for charts: polarArea, pie, and a doughnut. A label is either a single string, or it may be a string[] representing a multi-line label where each array element is on a new line.
  • chartType (ChartType) – indicates the type of charts, it can be: line, bar, radar, pie, polarArea, doughnut.
  • colors (Color[]) – data colors, will use the default and|or random colors if not specified (see below).
  • legend: (boolean = false) – if true show legend below the chart, otherwise not be shown.

Colors ng2-chart

Some colors are applied default, colors can be changed with colors attribute. However if data quantity is high, then colors generated randomly.

Events ng2-chart

  • chartHover: fires when mousemove (hover) on a chart has occurred, returns information regarding active points and labels.
  • chartClick: Fires when click on a chart has occurred, returns information regarding active points and labels.

Angular Line Chart Example with Chart js

A line chart is an unsophisticated chart type. It displays a graphical line to show a trend for a particular dimension. A line graph chart indicates diverse dimensions using multiple lines. It is considered best for showing changes in data for an extended period.

Here is the Line Chart example to articulately represent the changes in crude oil prices.

line-chart.component.ts

import { Component, } from '@angular/core';
import { ChartDataSets, ChartOptions } from 'chart.js';
import { Color, Label } from 'ng2-charts';

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})

export class LineChartComponent {

  lineChartData: ChartDataSets[] = [
    { data: [85, 72, 78, 75, 77, 75], label: 'Crude oil prices' },
  ];

  lineChartLabels: Label[] = ['January', 'February', 'March', 'April', 'May', 'June'];

  lineChartOptions = {
    responsive: true,
  };

  lineChartColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: 'rgba(255,255,0,0.28)',
    },
  ];

  lineChartLegend = true;
  lineChartPlugins = [];
  lineChartType = 'line';
  
}

Add following code in line-chart.component.html.

<div class="chartjs-block">
    <canvas baseChart 
        [datasets]="lineChartData" 
        [labels]="lineChartLabels" 
        [options]="lineChartOptions"
        [colors]="lineChartColors" 
        [legend]="lineChartLegend" 
        [chartType]="lineChartType" 
        [plugins]="lineChartPlugins">
    </canvas>
</div>

Here is the output:

Angular Line Chart Example with Chart js

Refresh ChartJS Data in Angular

Updating data in Char js is not that difficult. All it needs a simple function and the values those are needed to be updated.

 refreshData() {
    this.barChartData.data = [35, 38, 90, 20, 85, 276, 91]
 }

Create Responsive Charts in Angular

By default, the responsive property is set to true; the chart’s layout adapts the parent container size automatically and behaves autistically. However, you can update this option by setting up responsive property in lineChartOptions.

<canvas baseChart 
      height="400" 
      width="600" 
      [datasets]="lineChartData">
</canvas>

Bubble Chart in Angular Example

Bubble charts are awesome and depicts information through small round bubbles that generically floats in 3 dimesions. Each entity with its triplet of incorporated data is contrived as a disk that exposes two of the vᵢ values through the disk’s xy location and the third through its size.

Display investment equities in Angular Bubble chart.

bubble-chart.component.ts

import { Component, OnInit } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Color } from 'ng2-charts';

@Component({
  selector: 'app-bubble-chart',
  templateUrl: './bubble-chart.component.html',
  styleUrls: ['./bubble-chart.component.css']
})

export class BubbleChartComponent {

  public bubbleChartOptions: ChartOptions = {
    responsive: true,
    scales: {
      xAxes: [{
        ticks: {
          min: 0,
          max: 50,
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 50,
        }
      }]
    }
  };
  public bubbleChartType: ChartType = 'bubble';
  public bubbleChartLegend = true;

  public bubbleChartData: ChartDataSets[] = [
    {
      data: [
        { x: 15, y: 15, r: 15 },
        { x: 25, y: 15, r: 25 },
        { x: 36, y: 12, r: 33 },
        { x: 10, y: 18, r: 18 },
      ],
      label: 'Investment Equities',
    },
  ];

}

bubble-chart.component.html

<div class="chart-wrapper">
    <canvas baseChart
    [datasets]="bubbleChartData"
    [options]="bubbleChartOptions"
    [colors]="bubbleChartColors"
    [legend]="bubbleChartLegend"
    [chartType]="bubbleChartType">
  </canvas>
</div>

Check in the browser.

Bubble Chart in Angular Example

Pie Chart Example in Angular

A pie chart is useful for showing stats in an arch form. It is mainly divided data into slices with numeric proportion. The arc length of every slice is proportional to the quantity of information it depicts.

Here is the pie chart example that shows the movie’s data.

pie-chart.component.ts

import { Component } from '@angular/core';
import { ChartType, ChartOptions } from 'chart.js';
import { SingleDataSet, Label, monkeyPatchChartJsLegend, monkeyPatchChartJsTooltip } from 'ng2-charts';

@Component({
  selector: 'app-pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrls: ['./pie-chart.component.css']
})

export class PieChartComponent {

  public pieChartOptions: ChartOptions = {
    responsive: true,
  };
  public pieChartLabels: Label[] = [['SciFi'], ['Drama'], 'Comedy'];
  public pieChartData: SingleDataSet = [30, 50, 20];
  public pieChartType: ChartType = 'pie';
  public pieChartLegend = true;
  public pieChartPlugins = [];

  constructor() {
    monkeyPatchChartJsTooltip();
    monkeyPatchChartJsLegend();
  }

}

pie-chart.component.html

<div class="chart-wrapper">
    <canvas baseChart 
    [data]="pieChartData" 
    [labels]="pieChartLabels" 
    [chartType]="pieChartType"
    [options]="pieChartOptions"
    [plugins]="pieChartPlugins"
    [legend]="pieChartLegend">
  </canvas>
</div>

Output in the browser.

Pie Chart Example in Angular

Bar Chart Example in Angular

A bar chart shows the information using vertical bars. These vertical bars make the comparison vertically and horizontally. The following Bar Chart makes the best fruit data comparison graphically.

Place code in bar-chart.component.ts file.

import { Component } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';

@Component({
  selector: 'app-bar-chart',
  templateUrl: './bar-chart.component.html',
  styleUrls: ['./bar-chart.component.css']
})

export class BarChartComponent {

  barChartOptions: ChartOptions = {
    responsive: true,
  };
  barChartLabels: Label[] = ['Apple', 'Banana', 'Kiwifruit', 'Blueberry', 'Orange', 'Grapes'];
  barChartType: ChartType = 'bar';
  barChartLegend = true;
  barChartPlugins = [];

  barChartData: ChartDataSets[] = [
    { data: [45, 37, 60, 70, 46, 33], label: 'Best Fruits' }
  ];

}

bar-chart.component.html

<div class="chart-wrapper">
    <canvas baseChart 
    [datasets]="barChartData"
    [labels]="barChartLabels"
    [options]="barChartOptions"
    [plugins]="barChartPlugins"
    [legend]="barChartLegend"
    [chartType]="barChartType">
  </canvas>
</div>

Example in browser:

Bar Chart Example in Angular

Angular Doughnut Chart Example

A doughnut chart displays information in percentage for all the items, graphically its a circular chart with a hole at the center of it. Let’s depict the cars market share with the help of doughnut-chart.

doughnut-chart.component.ts

import { Component } from '@angular/core';
import { ChartType } from 'chart.js';
import { MultiDataSet, Label } from 'ng2-charts';

@Component({
  selector: 'app-doughnut-chart',
  templateUrl: './doughnut-chart.component.html',
  styleUrls: ['./doughnut-chart.component.css']
})

export class DoughnutChartComponent {

  doughnutChartLabels: Label[] = ['BMW', 'Ford', 'Tesla'];
  doughnutChartData: MultiDataSet = [
    [55, 25, 20]
  ];
  doughnutChartType: ChartType = 'doughnut';

}

Code goes in doughnut-chart.component.html file.

<div class="chart-wrapper">
    <canvas baseChart 
    [data]="doughnutChartData"
    [labels]="doughnutChartLabels"
    [chartType]="doughnutChartType">
  </canvas>
</div>

Final result in browser.

Angular Doughnut Chart Example

Angular Radar Chart Example

A radar chart is graphically the better way to depict multivariate data; with it, you can go for a two-dimensional graph or maybe three. Let’s bind employees’ skills in an angular radar char.

radar-chart.component.ts

import { Component } from '@angular/core';
import { ChartDataSets, ChartType, RadialChartOptions } from 'chart.js';
import { Label } from 'ng2-charts';

@Component({
  selector: 'app-radar-chart',
  templateUrl: './radar-chart.component.html',
  styleUrls: ['./radar-chart.component.css']
})

export class RadarChartComponent {

  public radarChartOptions: RadialChartOptions = {
    responsive: true,
  };
  public radarChartLabels: Label[] = ['Punctuality', 'Communication', 'Problem Solving',
    'Team Player', 'Coding', 'Technical Knowledge', 'Meeting Deadlines'];

  public radarChartData: ChartDataSets[] = [
    { data: [0, 1, 2, 3, 4, 5, 6], label: 'Employee Skill Analysis' }
  ];
  public radarChartType: ChartType = 'radar';

}

radar-chart.component.html

<div class="chart-wrapper">
    <canvas baseChart
    [datasets]="radarChartData"
    [options]="radarChartOptions"
    [labels]="radarChartLabels"
    [chartType]="radarChartType">
  </canvas>
</div>

Angular Radar Chart Example

Conclusion
Finally, the Angular Chart JS tutorial is over, i hope you must have liked this comprehensive tutorial. It heralds that you can easily create Line, Bubble, Pie, Bar, Doughnut, and Radar charts in angular. You can also customize the charts. Please do check the documentation of Charts.js and ng2-charts.