Visualizing data with NGX-Charts in Angular

Reading Time: 5 minutes

Data Science, Data Analytics, Big Data, these are the buzz words of today’s world. A huge amount of data is being generated and analyzed every day. So communicating the insights from that data becomes crucial. Charts help visualize the data and communicate the result of the analysis with charts, it becomes easy to understand the data.

There are a lot of libraries for angular that can be used to build charts. In this blog, we will look at one such library, NGX-Charts. We will see how to use it in angular and how to build data visualizations.

What we will cover:

  1. Installing ngx-chart.

  2. Building a vertical bar graph.

  3. Building a pie chart.

  4. Building an advanced pie chart.

A brief introduction about NGX-Charts

NGX-Chart charting framework for angular2+. It’s open-source and maintained by Swimlane.

NGX-Charts does not merely wrap d3, nor any other chart engine for that matter. 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, gauge charts, heatmap, treemap, and number cards.

Installation and Setup

1. Install the ngx-chart package in your angular app.

npm install @swimlane/ngx-charts --save

2. At the time of installing or when you serve your application is you get an error:

ERROR in The target entry-point "@swimlane/ngx-charts" has missing dependencies: - @angular/cdk/portal

You also need to install angular/cdk

npm install @angular/cdk --save

3. Import NgxChartsModule from ‘ngx-charts’ in AppModule

4. NgxChartModule also requires BrowserAnimationModule. Import is inAppModule.

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 { }

Amazing! Now we can start using ngx-chart component and build the graph we want.

In the AppComponent we will provide data that the chart will represent. It’s a sample data for vehicles on the road survey.

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  surveyData = [
    { name: 'Bikes', value: 105000 },
    { name: 'Cars', value: 55000 },
    { name: 'Trucks', value: 15000 },
    { name: 'Scooter', value: 150000 },
    { name: 'Bus', value: 20000 }
  ];
}

One thing to keep in mind that, ngx-charts always will expect the data in this form, which is an array of object {name: string, value: number}. The data cannot be always hardcoded like this. In your project, it might be coming from an API also. So in such cases, object type cannot be changed.

How to provide data to ngx-chart when it’s not in the form {name: string, value: number}[]?

At the end of this article I have given a trick to solve it, might come in handy.

Vertical Bar Chart

NgxChartModule gives a component ngx-chart-bar-vertical to make simple and beautiful bar charts.

app.component.html

<h3> Vertical Bar Chart</h3>
  <ngx-charts-bar-vertical
    [view]="[1000,400]"
    [results]="surveyData"
    [xAxisLabel]="'Count'"
    [legendTitle]="'Vehical Survey'"
    [yAxisLabel]="'Type of Vehicle'"
    [legend]="true"
    [showXAxisLabel]="true"
    [showYAxisLabel]="true"
    [xAxis]="true"
    [yAxis]="true"
    [gradient]="true">
  </ngx-charts-bar-vertical>

Ngx chart module gives us a pretty good amount of options to change the look of the chart according to the personal choice. Let’s take a look at the properties.

view: To set the [width, height] of the chart. if not specified it will take up adjust according to the parent element dimensions.

result: To render the data that we want the chart to represent.

xAxisLable, yAxisLabel: A label for x & y-axis

legend: Can be true or false. default is false.

showXAxisLabel, showYAxisLabel, xAxis, yAxis: Expects a boolean value, whether to show or not. (default is false)

gradient: Boolean value to tell whether the colors should be a gradient or solid plane.

In this example we are not given colors, we can also define custom colors

app.component.ts

colorScheme = {
    domain: ['#5AA454', '#C7B42C', '#AAAAAA']
  };

and in the <ngx-charts-bar-vertical> template give the property [scheme] this value.

There are many properties that can be modified, I encourage you to check out the official documentation for ngx-chart.

Pie Chart

We can generate advanced pie chart using < ngx-charts-advanced-pie-chart >  the component as below.

<h3>Pie Chart</h3>
<ngx-charts-pie-chart
  [results]="surveyData"
  [legend]="true"
  [legendTitle]="'Vehicle Survey'"
  [view]="[1000,300]"
  [labels]="true" >
</ngx-charts-pie-chart>

Advance Pie Chart

We can make a very amazing and complex pie chart using NGX-Chart in just a few lines, one such pie chart is the Advance Pie Chart which we can build using < ngx-charts-advanced-pie-chart > component as below.

<h3>Advance Pie Chart</h3>
<ngx-charts-advanced-pie-chart
  [results]="surveyData"
  [gradient]="true" >
</ngx-charts-advanced-pie-chart>

Great !!! we completed all our implementations and made some amazing looking charts pretty quickly.

Here is the full code of HTML and SCSS.

app.component.html

<div class=" container">
  <h1>Survey Reports</h1>
  <div>
    <h3> Vertical Bar Chart</h3>
    <ngx-charts-bar-vertical
      [gradient]="true"
      [legendTitle]="'Vehical Survey'"
      [legend]="true"
      [results]="surveyData"
      [showXAxisLabel]="true"
      [showYAxisLabel]="true"
      [view]="[1000,400]"
      [xAxisLabel]="'Count'"
      [xAxis]="true"
      [yAxisLabel]="'Type of Vehicle'"
      [yAxis]="true">
    </ngx-charts-bar-vertical>
  </div>

  <div>
    <h3>Pie Chart</h3>
    <ngx-charts-pie-chart
      [labels]="true"
      [legendTitle]="'Vehicle Survey'"
      [legend]="true"
      [results]="surveyData"
      [view]="[1000,300]">
    </ngx-charts-pie-chart>
  </div>

  <div>
    <h3>Advance Pie Chart</h3>
    <ngx-charts-advanced-pie-chart
      [gradient]="true"
      [results]="surveyData">
    </ngx-charts-advanced-pie-chart>
  </div>
</div>

app.component.scss

.container {
  display: flex;
  flex-direction: column;

  h3 {
    background-color: lightgrey;
    padding: 1.1em;
  }
}

Final result

What to do when the data type is different?

This might be trivial, but if you are new to angular this will help.

Suppose the data coming from the service is:

vehicleSurveyData = [
    {type: 'Bike', count: 105000},
    {type: 'Cars', count: 55000},
    {type: 'Trucks', count: 15000},
    {type: 'Scooter', count: 15000}
    {type: 'Bus', count: 20000'}
  ];

You can,

  1. Make a new empty array of type {name: string, value: number}.

  2. Use the map function on the vehicleSurveyData to iterate over each element of the array.

  3. Push just the value of the element to the empty array you created.

app.component.ts

export class AppComponent implements OnInit {
  surveyData = [];

  vehicleSurveyData = [
    {type: 'Bike', count: 105000},
    {type: 'Cars', count: 55000},
    {type: 'Trucks', count: 15000},
    {type: 'Scooter', count: 15000},
    {type: 'Bus', count: 20000}
  ];

  ngOnInit() {
    this.vehicleSurveyData.map(elem => this.surveyData.push({name: elem.type, value: elem.count}));
  }
}

To sum up

In this blog, we have seen how to install ngx-charts, how to use it to build data visualizations.

There a lot of charts you can build using ngx-charts, these were just a few. You can take the help of ngx-chart documentation.

I hope you liked and found this informative.

Leave a Reply