Wednesday, August 15, 2018

D3 Integration with Angular 6 Tutorial - Line Charts Example

In this posts, We are going to learn how to integrate D3js framework with angular/typescript technologies and display simple line chart using static data.
D3JS is a data drive document opensource javascript library for representing data in the visualized graphs.
Angular 6 is a front-end framework for javascript.

Prerequisite

  • Typescript 2.x
  • Angular  6.0
  • Npm - 5.6.0
  • Nodejs - v8.10.0
  • Angular cli 6.1.x
  • D3 - 5.50

Setup Nodejs and Angular-cli

First, Make sure that nodejs is installed, once nodejs is installed, Run below commands to test nodejs installation
C:\>npm --version
5.6.0
C:\>node --version
v8.10.0
Next is install latest angular-cli, ANgular cli is command line tool to generate the angular project. It will generate a readymade Angular application using Angular 6

npm install @angular/cli -g
Next check angular-cli version using ng command below

ng --version
Next step is to create an angular project using angular cli ng command

ng new linechartDemo
This generates angular 6 application code files and required configuration and installs all dependencies. Install D3js npm dependency locally

 npm install d3
This installs d3 dependencies and done below changes.

  1.  Installed d3 dependencies and created folders(d3,d3-array,d3-* ..etc) in root project/node_modules 
  2. Added d3 and its version information in the dependency section of the project/package.json file
"dependencies": {
 ....................
    "d3": "^5.5.0",
  
  }
Once dependencies are installed, Start the server using ng command
ng serve
Please see below diagram to access the server using URL localhost:4200
Angular and d3 linechart example

Create a New Component

 In Angular, Every functionality is represented in components. So we will create a new component for line chart Create a component for line chart
B:\d3Demo>ng generate component line-chart
CREATE src/app/line-chart/line-chart.component.html (29 bytes)
CREATE src/app/line-chart/line-chart.component.spec.ts (650 bytes)
CREATE src/app/line-chart/line-chart.component.ts (284 bytes)
CREATE src/app/line-chart/line-chart.component.css (0 bytes)
UPDATE src/app/app.module.ts (410 bytes)
This command does the following things.
Created below four files 
line-chart.component.html - Actual command HTML changes line-chart.component.spec.ts - this is typescript test file for a new component line-chart.component.ts - This is a typescript source file which contains component selector,templateUrl, and styleUrls and also has lifecycle callbacks methods line-chart.component.css - This file holds CSS style changes for a component
And also this command does update few changes.
The new component is configured in your Root module i.e app.module.ts. LineChartComponent is added in declarations section
 Please see below code for your information.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { LineChartComponent } from './line-chart/line-chart.component';

@NgModule({
  declarations: [
    AppComponent,
    LineChartComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
You can also create a component manually. But you have to well versed with typescript coding. Cli command allows developer job easy as it creates a prototype code for your project and adding required components

Import D3 modules into Angular components. 

To use D3 functionality, You need to import d3 components into your components. The below d3 components need to be extended

import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import * as d3Array from 'd3-array';
import * as d3Axis from 'd3-axis';
we are going to display Line Chart using static data The name says line graph used to represent data in series of points/markers connected by lines. The code changes are as below
line-chart.component.ts
import { Component, OnInit } from '@angular/core';

import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import * as d3Array from 'd3-array';
import * as d3Axis from 'd3-axis';

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {
    title = 'Line Chart';
    data: any[] = [
    {date: new Date('2010-01-01'), value: 80},
    {date: new Date('2010-01-04'), value: 90},
    {date: new Date('2010-01-05'), value: 95},
    {date: new Date('2010-01-06'), value: 100},
    {date: new Date('2010-01-07'), value: 110},
    {date: new Date('2010-01-08'), value: 120},
    {date: new Date('2010-01-09'), value: 130},
    {date: new Date('2010-01-10'), value: 140},
    {date: new Date('2010-01-11'), value: 150},
    ];

    private margin = {top: 20, right: 20, bottom: 30, left: 50};
    private width: number;
    private height: number;
    private x: any;
    private y: any;
    private svg: any;
    private line: d3Shape.Line<[number, number]>; // this is line defination

  constructor() { 
      // configure margins and width/height of the graph

   this.width = 960 - this.margin.left - this.margin.right;
        this.height = 500 - this.margin.top - this.margin.bottom;}

  ngOnInit() {
    this.buildSvg();
        this.addXandYAxis();
        this.drawLineAndPath();
  }
  private buildSvg() {
        this.svg = d3.select('svg')
            .append('g')
            .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');
    }
    private addXandYAxis() {
         // range of data configuring
         this.x = d3Scale.scaleTime().range([0, this.width]);
         this.y = d3Scale.scaleLinear().range([this.height, 0]);
         this.x.domain(d3Array.extent(this.data, (d) => d.date ));
         this.y.domain(d3Array.extent(this.data, (d) => d.value ));

        // Configure the Y Axis
        this.svg.append('g')
            .attr('transform', 'translate(0,' + this.height + ')')
            .call(d3Axis.axisBottom(this.x));
        // Configure the Y Axis
        this.svg.append('g')
            .attr('class', 'axis axis--y')
            .call(d3Axis.axisLeft(this.y));
    }

    private drawLineAndPath() {
        this.line = d3Shape.line()
            .x( (d: any) => this.x(d.date) )
            .y( (d: any) => this.y(d.value) );
        // Configuring line path
        this.svg.append('path')
            .datum(this.data)
            .attr('class', 'line')
            .attr('d', this.line);
    }

}

line-chart.component.html
<h2>{{ title }}</h2>
<svg width="900" height="500"></svg>
and the line chart is shown in the browser as below Angular Line Chart example using d3 Please like/share in it facebook/twitter and also leave a comment if you have any questions.

Related article


EmoticonEmoticon