Skip to main content

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way.

This helps businesses to grow more by taking important decisions from the data.

For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc.

In angular, we have various charting libraries to create charts. Ngx-charts is one of them.

Check out the list of best angular chart libraries

In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ?

We will see,

  • How to install ngx-charts in angular ?
  • Create a vertical bar chart
  • Create a pie chart, advanced pie chart and pie chart grid

ngx-charts is an open-source and declarative charting framework for angular2+. It is maintained by Swimlane.

It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis and shape generators, etc.

By having Angular do all of the renderings it opens us up to endless possibilities the Angular platform provides such as AoT, Universal, etc.

ngx-charts supports various chart types like bar charts, line charts, area charts, pie charts, bubble charts, doughnut charts, guage charts, heatmap, treemap and number cards.

It also supports features like autoscaling, timeline filtering, line interpolation, configurable axis, legends, real-time data support and so on.

  1. Create a new angular application using the following command 
    (Note: skip this step if you want to add ngx-charts in the existing angular application, At the time of writing this article I was using angular 9). 
    ng new ngx-charts-demo
  2. Install ngx-charts package in an angular application using the following command.
    npm install @swimlane/ngx-charts --save
  3. At the time of installation if you get the following error
    ERROR in The target entry-point "@swimlane/ngx-charts" has missing dependencies:
    - @angular/cdk/portal

    we need to add 

    @angular/cdk
     using the following

    npm install @angular/cdk --save
  4.  Import 
    NgxChartsModule
     from 
    'ngx-charts'
     in AppModule.
  5. ngx-charts also required the 
    BrowserAnimationsModule
    . Import it in 
    AppModule
    .

So our final 

AppModule
 will look like :

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgxChartsModule }from '@swimlane/ngx-charts';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
NgxChartsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Great, Installation steps are done. Now let’s develop various charts using 

ngx-charts
 components.

In 

AppComponent
 we will create the following sales data array. We will use this object to generate charts.

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
saleData = [
{ name: "Mobiles", value: 105000 },
{ name: "Laptop", value: 55000 },
{ name: "AC", value: 15000 },
{ name: "Headset", value: 150000 },
{ name: "Fridge", value: 20000 }
];
}

ngx-charts provides various components to generate vertical bar chart, pie chart, advanced pie chart, pie chart grid and so on.

To generate a vertical bar chart, 

ngx-charts
 provide 
ngx-charts-bar-vertical
 component, add it on the template as below:

<ngx-charts-bar-vertical
[view]="[1000,400]"
[results]="saleData"
[xAxisLabel]="'Products'"
[legendTitle]="'Product Sale Chart'"
[yAxisLabel]="'Sale'"
[legend]="true"
[showXAxisLabel]="true"
[showYAxisLabel]="true"
[xAxis]="true"
[yAxis]="true"
[gradient]="true">
</ngx-charts-bar-vertical>
Ngx-charts Vertical Bar Chart
Vertical Bar Chart of Sales Data

👉 Important properties of ngx-charts-bar-vertical component

  • results: To render salesData chart we need to assign this data object to results 
  • view: set width and height of chart view
  • xAxisLabel
  • legendTitle
  • legend : if you want to show legend set it to true, default it is false.
  • showXAxisLabel : set true to show x-axis label.
  • showYAxisLabel: set true to show y-axis label.
  • xAxis / xAxis : set true to show specific axis.
  • gradient: set it to true to show bar with gradient background. 

We can generate pie chart using 

< ngx-charts-pie-chart >
 component. add it in template as below.

<ngx-charts-pie-chart
[results]="saleData"
[legend]="true"
[legendTitle]="'Product Sale Report'"
[view]="[1000,300]"
[labels]="true" >
</ngx-charts-pie-chart>
Ngx-charts Pie Chart
Pie Chart of Sales Data

We can generate advanced pie chart using 

< ngx-charts-advanced-pie-chart >
 component as below.

<ngx-charts-advanced-pie-chart
[results]="saleData"
[gradient]="true" >
</ngx-charts-advanced-pie-chart>
advanced pie chart
Advanced Pie Chart Of Sales Data

To generate pie chart grid we need to 

< ngx-charts-pie-grid >
component on template as below.

<ngx-charts-pie-grid
[results]="saleData" >
</ngx-charts-pie-grid>
pie chart grid
Pie Chart Grid of Sales Data

Great !!! we are done with ngx-charts implementation✨✨✨.

app.module.ts
app.component.ts
app.component.html
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgxChartsModule }from '@swimlane/ngx-charts';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
NgxChartsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

In this article, We have seen data visualization with ngx-charts in angular application. We have installed the ngx-charts library and created various charts using sample data. 

Comments

Popular posts from this blog

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...