banner



How To Install Chart Js In Angular 7

In this Athwart tutorial, we'll discuss how to implement Chart.js library in an Angular x/9/viii/7/6/5/four project to create graphical interactive charts from data information. At that place is a wide diverseness of charts that can be used to represent data in the class of Line, Bar, Doughnut, Radar, Pie, Bubble, Scatter charts, etc.

This Angular post is uniform with Athwart 4 upto latest versions, Athwart vii, Angular 8, Angular 9, Angular 10, Angular 11 & Angular 12

Nearly Chart.js

Nautical chart.js is a popular charting library and creates several different kinds of charts using canvas on the HTML template. We tin easily create simple to avant-garde charts with static or dynamic data. They provide flexible configuration support to customize charts co-ordinate to need with color and smooth blitheness effects. It is known for its simple and beautiful looking charts which are very easy to apply.

Chart.js for Angular ii+

In Angular projects, the Nautical chart.js library is used with the ng2-charts package module. It is built to support Angular2+ projects and helps in creating awesome charts in Angular pages. The ng2-charts module provides 8 types of different charts including

  1. Line Chart
  2. Bar Chart
  3. Doughnut Chart
  4. Radar Chart
  5. Pie Nautical chart
  6. Polar Surface area Nautical chart
  7. Bubble Chart
  8. Besprinkle Nautical chart

On the way side, information technology also provides builtin Lite and Dark themes to use on charts.

Let's go started with the implementation…

Create an Angular Projection

We'll ready up a new Angular project using the Angular CLI tool. Run following npm command

            $ ng new angular-chartjs-tutorial ? Would you like to add Angular routing? Aye ? Which stylesheet format would you lot like to use? CSS          

Movement to the project directory

            $ cd angular-chartjs-tutorial          

To show all types of charts, we will create components for each type of chart. Run the ng generate command to create components

            $ ng generate component charts/line-chart $ ng generate component charts/bar-nautical chart $ ng generate component charts/doughnut-chart $ ng generate component charts/pie-chart $ ng generate component charts/bubble-area-chart $ ng generate component charts/scatter-expanse-chart          

Install and Configure the ng2-charts module in Athwart

At present, we will install the ng2-charts packet module in the Athwart project. Every bit a dependency, we'll as well need to install the nautical chart.js library to provide its method to create charts.

Run following npm control

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

After installation of ChartJs packages, nosotros need to import the ChartsModule in the app.module.ts file.

// app.module.ts ... ... import { ChartsModule } from 'ng2-charts';  @NgModule({   declarations: [     AppComponent,     ...     ...   ],   imports: [     BrowserModule,     AppRoutingModule,     ChartsModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }          

That's it now we are ready to apply CharJS charts in our Angular project.

Earlier we proceed let'southward accept a look on properties and options available in ng2-chart module.

Backdrop of ng2-chart

These properties are used to define or modify nautical chart elements.

  • data (SingleOrMultiDataSet) – set up of points of the chart, information technology should be MultiDataSet only for line, bar, radar and doughnut, otherwise SingleDataSet
  • datasets ({data: SingleDataSet, label: cord}[]) – data see about, the characterization for the dataset which appears in the legend and tooltips
  • labels (Characterization[]) – ten-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 exist a string[] representing a multi-line characterization 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
  • options (ChartOptions) – nautical chart options (every bit from Chart.js documentation)
  • colors (Color[]) – data colors will utilize a default and|or random colors if non specified (see below)
  • legend : (boolean = imitation) – if truthful prove legend below the chart, otherwise not exist shown

Events on ng2-chart

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

Colors on ng2-charts

At that place are prepare several default colors. Colors tin be replaced using the colors  attribute. If in that location is more data than colors, colors are generated randomly.

Creating Charts using ng2-charts

We tin can create a ChartJs chart on a template HTML by adding an <canvas> chemical element having baseChart directive with other properties nosotros discussed in a higher place. Let's check how to create different types of charts in the coming sections.

Line Chart Example in Athwart using Chart js

A line chart is the simplest nautical chart type, it shows a graphical line to stand for a trend for a dimension. A line graph or chart can have multiple lines to represent multiple dimensions. It is mainly used to brandish changes in data over time for single or multiple dimensions.

Hither we volition create a Line Chart example to graphically brandish the change in the sales of two Products A and B over fourth dimension.

Open the charts > line-chart > line-chart.component.tsand update with following code

            // line-chart.component.ts import { Component } from '@angular/core'; import { ChartDataSets, ChartOptions } from 'chart.js'; import { Colour, Characterization } from 'ng2-charts';  @Component({   selector: 'app-line-nautical chart',   templateUrl: './line-nautical chart.component.html',   styleUrls: ['./line-chart.component.css'] }) export class LineChartComponent {    // Array of different segments in chart   lineChartData: ChartDataSets[] = [     { information: [65, 59, 80, 81, 56, 55, 40], characterization: 'Product A' },     { data: [28, 48, 40, 19, 86, 27, xc], label: 'Product B' }   ];    //Labels shown on the x-axis   lineChartLabels: Label[] = ['Jan', 'February', 'March', 'April', 'May', 'June', 'July'];    // Ascertain chart options   lineChartOptions: ChartOptions = {     responsive: true   };    // Define colors of chart segments   lineChartColors: Color[] = [      { // dark grey       backgroundColor: 'rgba(77,83,96,0.two)',       borderColor: 'rgba(77,83,96,one)',     },     { // red       backgroundColor: 'rgba(255,0,0,0.3)',       borderColor: 'blood-red',     }   ];    // Prepare truthful to show legends   lineChartLegend = truthful;    // Define blazon of chart   lineChartType = 'line';    lineChartPlugins = [];    // events   chartClicked({ result, active }: { event: MouseEvent, agile: {}[] }): void {     console.log(event, active);   }    chartHovered({ event, active }: { event: MouseEvent, active: {}[] }): void {     console.log(event, active);   }  }                      

Adjacent, update the charts > line-nautical chart > line-chart.component.html file

            <div class="chartjs-container">     <canvas baseChart          [datasets]="lineChartData"          [labels]="lineChartLabels"          [options]="lineChartOptions"         [colors]="lineChartColors"          [legend]="lineChartLegend"          [chartType]="lineChartType"          [plugins]="lineChartPlugins"         (chartHover)="chartHovered($event)"          (chartClick)="chartClicked($event)">     </sail> </div>          

This creates a line chart, which volition await something like this

How to Refresh Information in Chart JS Angular?

Refreshing information in the ng2-charts is as simple equally assigning new values. In the to a higher place Line Chart js nautical chart, we tin refresh the data by using the lineChartData object as shown below:

                          refreshData() {     this.lineChartData[1].data = [28, 48, 140, xix, 86, 27, 90]   }          

This will simply update the Line nautical chart's 2nd line plot values to new values. Using this we tin can redraw the chart, rerender or merely refresh all is that simple.

Making Chart JS Responsive in Athwart

In the charts [options] property, we laissez passer the configuration object lineChartOptions. In that, we need to ready the responsive belongings to true. Past setting this to true, the chart will occupy its parent containers height and width.

To define the width & pinnacle in px, define information technology on the <canvas> element

<canvas baseChart        tiptop="300"        width="500"        [datasets]="lineChartData"> </canvas>

Pie Chart Example in Angular using Chart js

A pie chart looks like a pie where each slice represents a value. The data in a pie chart is displayed in a circle shape which is divided co-ordinate to the data passed. A Pie styled nautical chart is mainly used to prove values in percentage where each slice depicting each segment pct relative to other parts in total.

Permit's cheque how to create a Pie chart using Nautical chart js. Nosotros volition create a chart showing the composition of Air in percentage.

Open the charts > pie-chart > pie-nautical chart.component.ts file and update with following code

            // pie-chart.component.ts import { Component } from '@angular/core'; import { ChartOptions, ChartType } from 'chart.js'; import { Characterization } from 'ng2-charts';  @Component({   selector: 'app-pie-nautical chart',   templateUrl: './pie-chart.component.html',   styleUrls: ['./pie-chart.component.css'] }) export class PieChartComponent {    pieChartOptions: ChartOptions = {     responsive: true,     fable: {       position: 'top',     },     tooltips: {       enabled: true,       mode: 'unmarried',       callbacks: {         label: function (tooltipItems, information) {           return information.datasets[0].data[tooltipItems.index] + ' %';         }       }     },   };    pieChartLabels: Label[] = ['Nitrogen', 'Oxygen', 'Argon', 'Carbon dioxide'];    pieChartData: number[] = [78.09, 20.95, 0.93, 0.03];    pieChartType: ChartType = 'pie';    pieChartLegend = truthful;    pieChartPlugins = [];    pieChartColors = [     {       backgroundColor: ['rgba(255,0,0,0.3)', 'rgba(0,255,0,0.3)', 'rgba(0,0,255,0.iii)'],     },   ]; }          

Also, update the pie-chart.component.html file

            <div class="chartjs-container">     <canvas          baseChart          [data]="pieChartData"          [labels]="pieChartLabels"          [chartType]="pieChartType"         [options]="pieChartOptions"          [plugins]="pieChartPlugins"          [colors]="pieChartColors"          [legend]="pieChartLegend">     </canvass> </div>          

The Pie nautical chart using ChartJs volition look similar this

Bar Chart Example in Angular using ng2-charts

A bar nautical chart is consists of verticle bars that depict the comparison betwixt each other based on information provided. These bars can be aligned vertically besides to course columns.

Here we volition create a Bar nautical chart to testify the comparing of sales for Visitor A and Visitor B betwixt 2022 and 2022 years

Open the charts > bar-nautical chart > bar-chart.component.ts file and supersede with below lawmaking

            // bar-chart.component.ts import { Component } from '@angular/core'; import { ChartDataSets, ChartType, ChartOptions } from 'chart.js'; import { Label } from 'ng2-charts';  @Component({   selector: 'app-bar-nautical chart',   templateUrl: './bar-chart.component.html',   styleUrls: ['./bar-nautical chart.component.css'] }) export class BarChartComponent {    barChartOptions: ChartOptions = {     responsive: true,     scales: { xAxes: [{}], yAxes: [{}] },   };   barChartLabels: Label[] = ['2013', '2014', '2015', '2016', '2017', '2018'];   barChartType: ChartType = 'bar';   barChartLegend = true;   barChartPlugins = [];    barChartData: ChartDataSets[] = [     { data: [2500, 5900, 6000, 8100, 8600, 8050, 1200], label: 'Visitor A' },     { information: [2800, 4800, 4000, 7900, 9600, 8870, 1400], label: 'Company B' }   ];  }                      

Then update the bar-chart.component.html file

            <div class="chartjs-container">     <sheet baseChart          [datasets]="barChartData"          [labels]="barChartLabels"          [options]="barChartOptions"         [plugins]="barChartPlugins"          [legend]="barChartLegend"          [chartType]="barChartType">     </sail> </div>          

This component will create a Bar nautical chart which will look like this

Doughnut Nautical chart Case in Athwart using Chart js

A doughnut chart is a circular chart with a hole within it. Doughnut chart is used to represent data in the pct of a function in comparison to all items in total. Using Chartjs we can create a multi-layered doughnut chart with each 1 inside of the other.

Creating a doughnut nautical chart to representing the percentage of nigh liked game final years

Open the charts > doughnut-chart > doughnut-chart.component.ts and update with following code

            // doughnut-chart-component.ts import { Component } from '@angular/cadre'; import { Label, MultiDataSet, Color } from 'ng2-charts'; import { ChartType } from 'chart.js';  @Component({   selector: 'app-doughnut-chart',   templateUrl: './doughnut-chart.component.html',   styleUrls: ['./doughnut-chart.component.css'] }) export form DoughnutChartComponent {    doughnutChartLabels: Characterization[] = ['PUBG', 'Call of Duty', 'Fortnite'];   doughnutChartData: MultiDataSet = [     [53, 30, 17]   ];   doughnutChartType: ChartType = 'doughnut'; }                      

Now update the doughnut-chart.component.html file

            <div form="chartjs-container">     <sail baseChart      [data]="doughnutChartData"      [labels]="doughnutChartLabels"      [chartType]="doughnutChartType">     </canvas> </div>          

This will create a Doughnut nautical chart

Chimera Chart Instance in Athwart using Chart js

Chimera charts show values in the form of small circles that floats in 3 dimensions. Dissimilar the line or bar nautical chart, bubble charts are used to correspond values in three dimensions. Each item with its triplet of incorporated data is outlined equally a deejay that represents two of the six values through the deejay's XY location and the tertiary over its size.

Creating a bubble chart to show Units sold, Sales and Profitability

Open up the charts > bubble-chart > bubble-nautical chart.component.ts file and update information technology with below code

            // bubble-area-chart.component.ts import { Component } from '@angular/core'; import { ChartOptions, ChartType, ChartDataSets } from 'nautical chart.js';  @Component({   selector: 'app-bubble-area-nautical chart',   templateUrl: './bubble-area-chart.component.html',   styleUrls: ['./bubble-area-chart.component.css'] }) export class BubbleAreaChartComponent {    bubbleChartOptions: ChartOptions = {     responsive: true,     scales: {       xAxes: [         {           ticks: {             min: 0,             max: eighty,           }         }       ],       yAxes: [         {           ticks: {             min: 0,             max: 250000,           }         }       ]     }   };   bubbleChartType: ChartType = 'bubble';   bubbleChartLegend = true;    bubbleChartData: ChartDataSets[] = [     {       data: [         { x: 45, y: 150000, r: 22.22 },         { x: 42, y: 110000, r: 33.00 },         { x: threescore, y: 80637, r: fifteen.22 },         { x: 75, y: 195055, r: 21.50 },         { x: 30, y: 160446, r: 35.67 },       ],       characterization: 'Units sold, Sales and Profitability'     },   ]; }                      

Update the bubble.nautical chart.component.html file

            <div class="chartjs-container">     <sheet baseChart          [datasets]="bubbleChartData"          [options]="bubbleChartOptions"          [legend]="bubbleChartLegend"         [chartType]="bubbleChartType">     </sheet> </div>          

The Bubble chart component in Angular volition expect similar this

Besprinkle/Dot Nautical chart Example in Angular using Chart js

A Besprinkle plot uses dots to represent individual pieces of data. In statistics, these plots are useful to see if two variables are correlated to each other. A scatter chart is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically 2 variables for a ready of data.

To create a Besprinkle Dot chart, there is a representation of data related to Icecream sales vs Temperature.

Update the charts > scatter-area-chart > scatter-surface area-chart.component.ts file

            // besprinkle-area-chart.component.ts import { Component } from '@angular/core'; import { ChartOptions, ChartDataSets, ChartType } from 'nautical chart.js'; import { Label } from 'ng2-charts';  @Component({   selector: 'app-scatter-area-chart',   templateUrl: './besprinkle-area-chart.component.html',   styleUrls: ['./scatter-area-chart.component.css'] }) export class ScatterAreaChartComponent {    public scatterChartOptions: ChartOptions = {     responsive: true,   };    public scatterChartData: ChartDataSets[] = [     {       data: [         { x: 14.2, y: 215 },         { x: sixteen.4, y: 325 },         { x: eleven.nine, y: 185 },         { 10: 15.ii, y: 332 },         { 10: 18.5, y: 406 },         { 10: 22.one, y: 522 },         { x: 19.4, y: 412 },         { x: 25.1, y: 614 },         { x: 23.4, y: 544 },         { x: 18.i, y: 421 },       ],       label: 'Icecream sales vs Temperature',       pointRadius: ten,     },   ];   public scatterChartType: ChartType = 'scatter';  }                      

In the scatter-area-nautical chart.component.html template replace below code

            <div course="chartjs-container">     <canvas baseChart          [datasets]="scatterChartData"          [options]="scatterChartOptions"          [chartType]="scatterChartType">     </canvass> </div>          

The Scattered Dot chart volition plot similar this

Calculation All Charts in the App Component

Nosotros have created multiple types of Chart components higher up, at present we will add together all these charts at one dashboard and then that a user can view all these charts at a single glance.

To beautify the Dashboard, just include the bootstrap.css in the <caput> section of the alphabetize.html file.

            <head>   <!--meta files-->   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.four.one/css/bootstrap.min.css"> </head>          

At present open up the app.component.html file and implement the bootstrap Grid component with rows and columns every bit shown below

            <div class="container text-eye">   <h1>Angular Charts built using Chart.js</h1>    <div form="row">      <!-- Line -->     <div class="col-6">       <h4>Line Chart</h4>       <app-line-chart></app-line-chart>     </div>      <!-- Pie -->     <div class="col-half-dozen">       <h4>Pie Chart</h4>       <app-pie-chart></app-pie-chart>     </div>      <!-- Doughnut -->     <div form="col-6">       <h4>Doughnut Nautical chart</h4>       <app-doughnut-chart></app-doughnut-chart>     </div>      <!-- Bar -->     <div class="col-6">       <h4>Bar Chart</h4>       <app-bar-nautical chart></app-bar-chart>     </div>      <!-- Bubble -->     <div class="col-6">       <h4>Bubble Chart</h4>       <app-chimera-area-chart></app-bubble-area-nautical chart>     </div>      <!-- Scatter -->     <div class="col-vi">       <h4>Besprinkle Chart</h4>       <app-scatter-area-chart></app-scatter-area-chart>     </div>    </div>  </div>          

Finally, we accept created a cute and cool looking dashboard as well with half dozen types of near popular types of Charts using the Chartjs library. These components can be used anywhere equally required bypassing dynamic data values using services or @input decorators.

Observe source code of this project in GitHub repo

Conclusion: That's information technology, we just implemented Chart JS library in our Angular ix/8 project past using the ng2-charts package and created various types of charts similar Line,Bar, Pie, Doughnut, etc. We can easily correspond uncomplicated data into graphical UI charts by using Chartjs.  Y'all can go more information in the official Char.js and ng2-charts documentations.

Source: https://www.freakyjolly.com/angular-chart-js-tutorial-using-ng2-charts-with-examples/

Posted by: campbellthisil.blogspot.com

0 Response to "How To Install Chart Js In Angular 7"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel