Top Related Projects
Simple HTML5 Charts using the <canvas> tag
📊 Interactive JavaScript Charts built on SVG
Highcharts JS, the JavaScript charting framework
Bring data to life with SVG, Canvas and HTML. :bar_chart::chart_with_upwards_trend::tada:
Open-source JavaScript charting library behind Plotly and Dash
Redefined chart library built with React and D3
Quick Overview
ng2-charts is a popular Angular library that provides a set of directives for creating various types of charts using Chart.js. It simplifies the process of integrating Chart.js into Angular applications, offering a more Angular-friendly approach to chart creation and manipulation.
Pros
- Easy integration with Angular projects
- Supports a wide range of chart types (line, bar, pie, doughnut, etc.)
- Reactive updates when data changes
- Customizable appearance and behavior
Cons
- Limited to Chart.js functionality
- Learning curve for those unfamiliar with Chart.js
- May require additional setup for advanced customizations
- Documentation could be more comprehensive
Code Examples
- Creating a basic line chart:
import { Component } from '@angular/core';
import { ChartConfiguration } from 'chart.js';
@Component({
selector: 'app-line-chart',
template: '<canvas baseChart [data]="lineChartData" [options]="lineChartOptions" type="line"></canvas>'
})
export class LineChartComponent {
public lineChartData: ChartConfiguration['data'] = {
datasets: [
{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
],
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July']
};
public lineChartOptions: ChartConfiguration['options'] = {
responsive: true
};
}
- Creating a bar chart with multiple datasets:
import { Component } from '@angular/core';
import { ChartConfiguration } from 'chart.js';
@Component({
selector: 'app-bar-chart',
template: '<canvas baseChart [data]="barChartData" [options]="barChartOptions" type="bar"></canvas>'
})
export class BarChartComponent {
public barChartData: ChartConfiguration['data'] = {
datasets: [
{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
{ data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' }
],
labels: ['2016', '2017', '2018', '2019', '2020', '2021', '2022']
};
public barChartOptions: ChartConfiguration['options'] = {
responsive: true
};
}
- Updating chart data dynamically:
import { Component } from '@angular/core';
import { ChartConfiguration } from 'chart.js';
@Component({
selector: 'app-dynamic-chart',
template: `
<canvas baseChart [data]="chartData" [options]="chartOptions" type="line"></canvas>
<button (click)="updateData()">Update Data</button>
`
})
export class DynamicChartComponent {
public chartData: ChartConfiguration['data'] = {
datasets: [{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' }],
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']
};
public chartOptions: ChartConfiguration['options'] = {
responsive: true
};
updateData() {
this.chartData.datasets[0].data = [
Math.round(Math.random() * 100),
Math.round(Math.random() * 100),
Math.round(Math.random() * 100),
Math.round(Math.random() * 100),
Math.round(Math.random() * 100),
Math.round(Math.random() * 100),
Math.round(Math.random() * 100)
];
// Trigger change detection
this.chartData = {...this.chartData};
}
}
Competitor Comparisons
Simple HTML5 Charts using the <canvas> tag
Pros of Chart.js
- More versatile and can be used with various frameworks, not limited to Angular
- Larger community and more frequent updates
- Offers more chart types and customization options out of the box
Cons of Chart.js
- Requires more setup and configuration when used with Angular
- May have a steeper learning curve for Angular developers
- Lacks built-in Angular-specific features and optimizations
Code Comparison
ng2-charts:
import { NgChartsModule } from 'ng2-charts';
@NgModule({
imports: [NgChartsModule],
// ...
})
export class AppModule { }
Chart.js:
import { Chart } from 'chart.js/auto';
ngOnInit() {
const ctx = document.getElementById('myChart');
new Chart(ctx, {
// chart configuration
});
}
ng2-charts provides a more Angular-friendly approach with its module system and directives, while Chart.js requires manual instantiation and configuration within Angular components. ng2-charts simplifies the integration process for Angular developers, but Chart.js offers more flexibility for use across different frameworks and vanilla JavaScript projects.
Both libraries are based on Chart.js under the hood, but ng2-charts adds an Angular-specific wrapper to streamline the development process in Angular applications. The choice between the two depends on the specific project requirements, developer preferences, and the need for Angular-specific optimizations versus broader framework compatibility.
📊 Interactive JavaScript Charts built on SVG
Pros of ApexCharts.js
- More extensive chart types and customization options
- Better performance with large datasets
- Responsive and mobile-friendly design out of the box
Cons of ApexCharts.js
- Steeper learning curve due to more complex API
- Larger file size, which may impact load times
- Not specifically designed for Angular integration
Code Comparison
ng2-charts:
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';
public barChartOptions: ChartOptions = { responsive: true };
public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010'];
public barChartType: ChartType = 'bar';
public barChartData: ChartDataSets[] = [
{ data: [65, 59, 80, 81, 56], label: 'Series A' }
];
ApexCharts.js:
var options = {
chart: { type: 'bar' },
series: [{
name: 'Series A',
data: [65, 59, 80, 81, 56]
}],
xaxis: {
categories: ['2006', '2007', '2008', '2009', '2010']
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
Both libraries offer powerful charting capabilities, but ApexCharts.js provides more flexibility and chart types at the cost of a steeper learning curve. ng2-charts is more tightly integrated with Angular, making it easier to use in Angular projects. The choice between them depends on the specific project requirements and the developer's familiarity with Angular and charting libraries.
Highcharts JS, the JavaScript charting framework
Pros of Highcharts
- More extensive and feature-rich charting library with a wide variety of chart types
- Better documentation and community support
- Highly customizable with advanced options for styling and interactivity
Cons of Highcharts
- Commercial license required for most use cases
- Steeper learning curve due to its extensive API and options
- Larger file size, which may impact page load times
Code Comparison
ng2-charts:
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';
public barChartOptions: ChartOptions = { responsive: true };
public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010'];
public barChartType: ChartType = 'bar';
public barChartData: ChartDataSets[] = [
{ data: [65, 59, 80, 81, 56], label: 'Series A' }
];
Highcharts:
import * as Highcharts from 'highcharts';
const options: Highcharts.Options = {
chart: { type: 'bar' },
title: { text: 'Bar Chart' },
xAxis: { categories: ['2006', '2007', '2008', '2009', '2010'] },
series: [{ name: 'Series A', data: [65, 59, 80, 81, 56] }]
};
Highcharts.chart('container', options);
Both libraries offer ways to create charts, but Highcharts provides more built-in options and customization out of the box, while ng2-charts relies more on Chart.js configurations.
Bring data to life with SVG, Canvas and HTML. :bar_chart::chart_with_upwards_trend::tada:
Pros of d3
- Highly flexible and customizable, allowing for complex and unique visualizations
- Extensive documentation and large community support
- Can be used with various frameworks or vanilla JavaScript
Cons of d3
- Steeper learning curve due to its low-level nature
- Requires more code to create basic charts compared to ng2-charts
- May be overkill for simple charting needs
Code Comparison
ng2-charts:
<canvas baseChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[legend]="barChartLegend"
[chartType]="'bar'">
</canvas>
d3:
const svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", (d, i) => i * 30)
.attr("y", d => height - d * 4)
.attr("width", 25)
.attr("height", d => d * 4);
Summary
d3 offers more power and flexibility for creating custom visualizations but requires more effort and expertise. ng2-charts provides a simpler, more Angular-friendly approach for basic charting needs. The choice between the two depends on the complexity of the visualizations required and the developer's familiarity with each library.
Open-source JavaScript charting library behind Plotly and Dash
Pros of plotly.js
- More extensive chart types and customization options
- Standalone library, not tied to a specific framework
- Active development with frequent updates and improvements
Cons of plotly.js
- Larger file size, potentially impacting load times
- Steeper learning curve due to more complex API
- May require additional setup for Angular integration
Code Comparison
ng2-charts:
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';
public barChartOptions: ChartOptions = { responsive: true };
public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010'];
public barChartType: ChartType = 'bar';
public barChartData: ChartDataSets[] = [
{ data: [65, 59, 80, 81, 56], label: 'Series A' }
];
plotly.js:
import Plotly from 'plotly.js-dist';
const data = [{
x: ['2006', '2007', '2008', '2009', '2010'],
y: [65, 59, 80, 81, 56],
type: 'bar'
}];
const layout = { title: 'Bar Chart' };
Plotly.newPlot('myDiv', data, layout);
Summary
plotly.js offers more flexibility and chart types but comes with a larger footprint and complexity. ng2-charts is more Angular-friendly and easier to use but has fewer features. The choice depends on project requirements and developer preferences.
Redefined chart library built with React and D3
Pros of recharts
- Built specifically for React, offering seamless integration with React applications
- Highly customizable with a wide range of chart types and components
- Responsive design out of the box, adapting to different screen sizes
Cons of recharts
- Limited to React applications, not suitable for Angular projects
- Steeper learning curve for developers unfamiliar with React concepts
- May require more manual configuration for complex chart scenarios
Code Comparison
ng2-charts (Angular):
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';
@Component({
selector: 'app-bar-chart',
template: '<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]="barChartType"></canvas>'
})
recharts (React):
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
const MyBarChart = ({ data }) => (
<BarChart width={600} height={300} data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="value" fill="#8884d8" />
</BarChart>
);
Both libraries offer powerful charting capabilities, but ng2-charts is tailored for Angular applications, while recharts is designed specifically for React projects. The choice between them largely depends on the framework being used and the specific requirements of the project.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ng2-charts slack
Beautiful charts for Angular based on Chart.js
Usage & Demo
Samples using ng2-charts
https://valor-software.com/ng2-charts/
Installation
You can install ng2-charts by using the Angular CLI:
ng add ng2-charts
The required packages will be automatically installed, and your app.config.ts
will be updated with the required
changes to start using the library right away.
Manual install through package managers
-
You can install ng2-charts using npm:
npm install ng2-charts --save
or yarn:
yarn add ng2-charts --save
-
You will also need to install and include
Chart.js
library in your application (it is a peer dependency of this library, more info can be found in the officialchart.js
documentation)npm install chart.js --save
or with yarn:
yarn add chart.js --save
-
Import the directive in your standalone component:
import { BaseChartDirective } from 'ng2-charts'; @Component({ standalone: true, imports: [BaseChartDirective], }) export class MyComponent {}
-
Provide a configuration, typically in your
main.ts
:import { provideCharts, withDefaultRegisterables } from 'ng2-charts'; bootstrapApplication(AppComponent, { providers: [provideCharts(withDefaultRegisterables())], }).catch((err) => console.error(err));
Alternatively, include a minimal configuration to reduce the bundle size, eg:
provideCharts({ registerables: [BarController, Legend, Colors] });
Or in your AppModule:
import { provideCharts, withDefaultRegisterables } from 'ng2-charts'; @NgModule({ providers: [provideCharts(withDefaultRegisterables())], bootstrap: [AppComponent], }) export class AppModule {}
Angular version compatibility table
ng2-chart version | ||||||
Angular version | v1.x | v2.x | v3.x | v4.x | v5.x | v6.x |
2 - 9 | â | |||||
10 | â | |||||
11 | â | |||||
12 | â | |||||
13 | â | |||||
14 | â | â | ||||
15 | â | â | ||||
16 | â | |||||
17 | â | â |
API
Chart types
There is one directive for all chart types: baseChart
, and there are 8 types of charts: line
, bar
, radar
, pie
, polarArea
, doughnut
, bubble
and scatter
. You can use the directive on a canvas
element as follows:
<canvas baseChart [data]="barChartData" [options]="barChartOptions" [type]="'bar'"> </canvas>
Properties
Note: For more information about possible options please refer to original chart.js documentation
type
: (ChartType
) - indicates the type of chart, it can be:line
,bar
,radar
,pie
,polarArea
,doughnut
or any custom type added to Chart.jsdata
: (ChartData<TType, TData, TLabel>
) - the whole data structure to be rendered in the chart. Support different flexible formats and parsing options, see here. In alternative, and depending on thetype
of your chart, you can use thelabels
anddatasets
properties to specify individual options.labels
: (TLabel[]
) - Datasets labels. It's necessary for charts:line
,bar
andradar
. And just labels (on hover) for charts:polarArea
,pie
anddoughnut
. Labels are matched in order with thedatasets
array.datasets
: (ChartDataset<TType, TData>[]
) - Same as thedatasets
property of thedata
input. See here for details.options
: (ChartOptions<TType>
) - chart options (as per chart.js documentation).legend
: (boolean = false
) - if true, chart legend is shown.
Events
chartClick
: fires when click on a chart has occurred, returns information regarding active points and labelschartHover
: fires when mousemove (hover) on a chart has occurred, returns information regarding active points and labels
Colors
By default, this library uses the colors as defined by Chart.js. If you need more control on colors, eg: generating colors on the fly, see the advanced color palettes.
Dynamic Theming
The ThemeService
allows clients to set a structure specifying colors
override settings. This service may be called when the dynamic theme changes, with colors which fit the theme. The
structure is interpreted as an override, with special functionality when dealing with arrays. Example:
type Theme = 'light-theme' | 'dark-theme';
private _selectedTheme: Theme = 'light-theme';
public get selectedTheme(){
return this._selectedTheme;
}
public set selectedTheme(value){
this._selectedTheme = value;
let overrides: ChartOptions;
if (this.selectedTheme === 'dark-theme') {
overrides = {
legend: {
labels: { fontColor: 'white' }
},
scales: {
xAxes: [ {
ticks: { fontColor: 'white' },
gridLines: { color: 'rgba(255,255,255,0.1)' }
} ],
yAxes: [ {
ticks: { fontColor: 'white' },
gridLines: { color: 'rgba(255,255,255,0.1)' }
} ]
}
};
} else {
overrides = {};
}
this.themeService.setColorschemesOptions(overrides);
}
constructor(private themeService: ThemeService<AppChartMetaConfig>){
}
setCurrentTheme(theme: Theme){
this.selectedTheme = theme;
}
The overrides
object has the same type as the chart options object ChartOptions
, and wherever a simple field is
encountered it replaces the matching field in the options
object. When an array is encountered (as in the xAxes
and yAxes
fields above), the single object inside the array is used as a template to override all array elements in
the matching field in the options
object. So in the case above, every axis will have its ticks and gridline colors
changed.
Troubleshooting
Please follow this guidelines when reporting bugs and feature requests:
- Use GitHub Issues to report bugs and feature requests.
- Please always provide an example project and write steps to reproduce the error. That way we can focus on fixing the bug, not scratching our heads trying to reproduce it.
Thanks for understanding!
License
The MIT License (see the LICENSE file for the full text)
If you like this library and want to say thanks, consider buying me a coffee!
Top Related Projects
Simple HTML5 Charts using the <canvas> tag
📊 Interactive JavaScript Charts built on SVG
Highcharts JS, the JavaScript charting framework
Bring data to life with SVG, Canvas and HTML. :bar_chart::chart_with_upwards_trend::tada:
Open-source JavaScript charting library behind Plotly and Dash
Redefined chart library built with React and D3
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot