DEV Community

David Akim
David Akim

Posted on

Using Plotly.js with Angular

In this lesson, we will go through the steps of integrating Plotly.js with Angular. Plotly.js is an Open Source Graphing Library. At the end of the lesson you should be able to do a simple plot with Plotly.js.

Prerequisite

  • Must be familiar with Angular

Create a new angular project called angular-plotly. In the command terminal type the following.

ng new angular-plotly
Enter fullscreen mode Exit fullscreen mode

When prompted “Would you like to add Angular routing? (y/N)”, you can type either y or N and hit Enter on the keyboard. When prompted “Which stylesheet format would you like to use?”, you can select CSS.

Navigate into the angular-plotly directory. In the command terminal type the following.

cd angular-plotly
Enter fullscreen mode Exit fullscreen mode

Create a new component called plotly-component. In the command terminal type the following.

ng generate component plotly-component
Enter fullscreen mode Exit fullscreen mode

Open app.component.html ,delete all the contents and add the following line

<app-plotly-component></app-plotly-component>
Enter fullscreen mode Exit fullscreen mode

Go to Plotly.js. There will be 3 options:

  • Install from NPM
  • Use CDN link
  • Download Plotly.js

For this demonstration, download Plotly.js.

Copy the downloaded file into the assets folder of your angular project, which is located at angular-plotly/src/assets.

Open the angular.json file and modify lines 35 and 104 as seen below.

"scripts": ["src/assets/plotly-2.14.0.min.js"]
Enter fullscreen mode Exit fullscreen mode

If you are having difficulty finding the specific lines to modify, simply search for the keyword scripts. Please note at the time of writing this article the name of the script is plotly-2.14.0.min.js. The name of your script may vary. This is the complete code.

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "cli": {
    "analytics": false
  },
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-plotly": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:application": {
          "strict": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-plotly",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": [
              "src/assets/plotly-2.14.0.min.js"
            ]
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "angular-plotly:build:production"
            },
            "development": {
              "browserTarget": "angular-plotly:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular-plotly:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": [
              "src/assets/plotly-2.14.0.min.js"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "angular-plotly"
}
Enter fullscreen mode Exit fullscreen mode

Create a new service called plotly. This service will contain the plot functions. In the command terminal type the following.

ng generate service plotly
Enter fullscreen mode Exit fullscreen mode

Open plotly.service.ts and make the following changes.

import { Injectable } from '@angular/core';declare let Plotly: any;
Enter fullscreen mode Exit fullscreen mode

In plotly.service.ts create a new function called plotLine. This function accepts 4 arguments. The title argument is the title of the plot and plotDiv is the id of the div tag used for displaying the plot. The x and y arrays contain the plot data. This is the complete code.

import { Injectable } from '@angular/core';
declare let Plotly: any;@Injectable({
  providedIn: 'root'
})
export class PlotlyService {constructor() { }plotLine(title: string, plotDiv: string, x:number[], y:number[]){           
    let trace = {
      x: x,    
      y: y,   
      type: 'scatter'   
    };

    let layout = {
      title:title
    };

    Plotly.newPlot(plotDiv, [trace], layout);     
  }}
Enter fullscreen mode Exit fullscreen mode

Open plotly-component.component.ts and make the following changes. When the page loads, a straight line will be plotted. Here the title of the plot is “Line Plot”. The id of the div displaying the plot is “plot”. The x and y values are 1,2,3,4,5.

import { Component, OnInit } from '@angular/core';
import { PlotlyService } from '../plotly.service';@Component({
  selector: 'app-plotly-component',
  templateUrl: './plotly-component.component.html',
  styleUrls: ['./plotly-component.component.css']
})
export class PlotlyComponentComponent implements OnInit {constructor(private plot:PlotlyService) { }ngOnInit(): void {
    let x:number[] = [1,2,3,4,5];
    let y:number[] = [1,2,3,4,5];
    this.plot.plotLine("Line Plot","plot",x,y);
  }}
Enter fullscreen mode Exit fullscreen mode

Open plotly-component.component.html and make the following changes. Here the div with the id plot is created.

<div id="plot"></div>
Enter fullscreen mode Exit fullscreen mode

In the command terminal type the following.

ng serve
Enter fullscreen mode Exit fullscreen mode

On your browser go to http://localhost:4200/. You should see the plot.

Image description

This is the end of the lesson. For more information on Plotly.js, check the documentation Plotly.

Top comments (0)