How to use highcharts with angular 5? - highcharts

Is there any way to use highcharts.js with angular2 ?Is there any option available instead of highcharts?

You could also try angular2-highcharts I implemented.

I know this question is a bit stale, but is one of the first hits for angular2+highcharts queries... It's pretty simple and straight forward to get highcharts working. Here is a plunker example, https://plnkr.co/edit/8ccBrP?p=preview.
Here is the main logic:
import {
Component,
ElementRef,
AfterViewInit,
OnDestroy,
ViewChild
} from '#angular/core';
const Highcharts = require('highcharts/highcharts.src');
import 'highcharts/adapters/standalone-framework.src';
#Component({
selector: 'my-app',
template: `
<div>
<div #chart></div>
</div>
`
})
export class AppComponent implements AfterViewInit, OnDestroy {
#ViewChild('chart') public chartEl: ElementRef;
private _chart: any;
public ngAfterViewInit() {
let opts: any = {
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
name: 'Tokyo',
data: [
7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2,
26.5, 23.3, 18.3, 13.9, 9.6
]
}]
};
if (this.chartEl && this.chartEl.nativeElement) {
opts.chart = {
type: 'line',
renderTo: this.chartEl.nativeElement
};
this._chart = new Highcharts.Chart(opts);
}
}
public ngOnDestroy() {
this._chart.destroy();
}
}

I think that you could try ng2-highchart (https://github.com/Bigous/ng2-highcharts).
See this project for a sample of use: https://github.com/Bigous/angular2-seed-ng2-highcharts.
How to set it up in SystemJS configuration: https://github.com/Bigous/angular2-seed-ng2-highcharts/blob/master/src/index.html#L43 and https://github.com/Bigous/angular2-seed-ng2-highcharts/blob/master/tools/config.ts#L108
<script>
System.config({
map: {
'ng2-highchart': 'node_modules/ng2-highchart'
},
(...)
});
</script>
How to configure it within a component: https://github.com/Bigous/angular2-seed-ng2-highcharts/blob/master/src/home/components/home.ts#L10
import {Component, OnInit} from 'angular2/core';
import {Http} from 'angular2/http';
import {Ng2Highcharts, Ng2Highmaps, Ng2Highstocks} from 'ng2-highcharts/ng2-highcharts';
#Component({
selector: 'home',
moduleId: module.id,
templateUrl: './home.html',
styleUrls: ['./home.css'],
directives: [Ng2Highcharts, Ng2Highmaps, Ng2Highstocks]
})
export class HomeCmp implements OnInit {
(...)
}
How to use it within a component template: https://github.com/Bigous/angular2-seed-ng2-highcharts/blob/master/src/home/components/home.html#L9
<div [ng2-highcharts]="chartOptions" class="graph"></div>

To install this library, install peer dependencies first:
$ npm install --save highcharts#^4.2.1
Also, make sure you install the typings for Highcharts:
$ npm install #types/highcharts --save
Then, install this library running:
$ npm install --save ng2-highcharts
app.module
import { Ng2HighchartsModule } from 'ng2-highcharts';
add Ng2HighchartsModule to #NgModule => imports
angular cli Add this JS files in script
"../node_modules/highcharts/highcharts.js",
"../node_modules/highcharts/highcharts-more.js",
"../node_modules/highcharts/modules/exporting.js"
component file
import { Ng2Highcharts } from 'ng2-highcharts';
private chartData = {
chart: {
type: 'column'
},
xAxis: {
categories: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
},
series: [
{
name: 'NC',
data: [7057, 6858, 6643, 6570, 6115, 107, 31, 635, 203, 2, 2]
}, {
name: 'OK',
data: [54047, 52484, 50591, 49479, 46677, 33, 156, 947, 408, 6, 2]
}, {
name: 'KO',
data: [11388, 11115, 10742, 10757, 10290, 973, 914, 4054, 732, 34, 2]
}, {
name: 'VALID',
data: [8836, 8509, 8255, 7760, 7621, 973, 914, 4054, 732, 34, 2]
}, {
name: 'CHECK',
data: [115, 162, 150, 187, 172, 973, 914, 4054, 732, 34, 2]
}, {
name: 'COR',
data: [12566, 12116, 11446, 10749, 10439, 973, 914, 4054, 732, 34, 2]
}
]};
And the HTML
<div [ng2-highcharts]="chartData"></div>

Added this to package.json:
"angular2-highcharts": "^0.3.3",
"highcharts": "^5.0.0",
Added this on main.module.ts file:
import { ChartModule } from 'angular2-highcharts';
Added this on main.module.ts in #NgModule imports section
imports: [ // import Angular's modules
ChartModule
],
Added this in vendor.ts file:
//Angular2-highcharts
import { Highcharts } from 'angular2-highcharts';
require('highcharts/highcharts-more')(Highcharts);
require('highcharts/modules/solid-gauge')(Highcharts);
Added this on the chart.component.ts file
import { Highcharts } from 'angular2-highcharts';
declare this on inside the chart.component class code:
options: HighchartsOptions;
chartData: any = [];
Add this code in the method that binds the data to the chart:
this.options = {
chart: { type: 'spline' },
title : { text : 'chart' },
xAxis: {
type: 'datetime'
},
series: [{
name: "name",
data: this.chartData
}]
};
Added this on the chart.component.html page:
<div>
<chart [options]="options"></chart>
</div>

I didn't tested yet but HighCharts has its official Angular library which seems to be actively maintained.

PrimeNG charts can be an alternative. http://www.primefaces.org/primeng/

Try this approach without need of 3rd party library.
import {Component} from 'angular2/core';
declare var jQuery:any;
#Component({
selector: 'my-chart',
template: `<div style="width:60%" id="container"></div>`
})
export class AppComponent {
private data = [
{
name: 'USA',
data: [null, null, null, null, null, 6, 11, 32, 110, 235, 369, 640,
1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468, 20434, 24126,
27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662,
26956, 27912, 28999, 28965, 27826, 25579, 25722, 24826, 24605,
24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344, 23586,
22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950,
10871, 10824, 10577, 10527, 10475, 10421, 10358, 10295, 10104]
},
{
name: 'USSR/Russia',
data: [null, null, null, null, null, null, null, null, null, null,
5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471, 3322,
4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478,
15915, 17385, 19055, 21205, 23044, 25393, 27935, 30062, 32049,
33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000,
35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000,
21000, 20000, 19000, 18000, 18000, 17000, 16000]
}];
ngAfterViewInit() {
this.renderChart();
}
renderChart(){
jQuery('#container').highcharts({
chart: {
type: 'area'
},
title: {
text: 'US and USSR nuclear stockpiles'
},
subtitle: {
text: 'Source: thebulletin.metapress.com'
},
xAxis: {
allowDecimals: false,
labels: {
formatter: function () {
return this.value;
}
}
},
yAxis: {
title: {
text: 'Nuclear weapon states'
},
labels: {
formatter: function () {
return this.value / 1000 + 'k';
}
}
},
tooltip: {
pointFormat: '{series.name} produced <b>{point.y:,.0f}</b>' +
'<br/>warheads in {point.x}'
},
plotOptions: {
area: {
pointStart: 1940,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: true
}
}
}
}
},
series: this.data
});
}
}
And put down this to index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
Or try this module http://ngmodules.org/modules/angular2-highcharts, if you need to handle on point select event.

As of October 2018:
angular-highcharts is the new kid on the block and has overtaken angular2-highcharts in popularity.
angular-highcharts is an Angular directive based implementation of highcharts and ATTOW requires Angular 7 (which was released very recently)
I have no affiliation to either library.

With usage of official highcharts module only (w/o angular2-highcharts and other and even #types/highcharts)
npm install --save-dev highcharts
import * as HC from 'highcharts';
...
export class MainComponent implements OnInit, AfterViewInit {
...
ngAfterViewInit() {
let chartOptions = {
...
chart: {
renderTo: 'chartPanel', // need to have div #chartPanel in template
...
}
}
this.chartInstance = new HC.Chart(chartOptions);
}
this.chartInstance will have all highcharts methods like addSeries, reflow, redraw etc.

Related

Highcharts Formatting Axes, Labels & Tooltips

I'm evaluating Highcharts and I'm struggling to format my axes and data labels correctly. On the tooltip object for a series I can set the prefix, suffix and decimals ( this is wonderful ). I cannot find similar options for data labels and the axes?
What is the correct way to format the axis, tooltips and labels to all use the correct prefix, suffix, decimals and use a comma for the thousands separator? Is there a single place this can be set to be inherited?
I have tried using a formatter on data labels but I've been unable to implement it as it does not know what "this" is.
Below is my example using a new angular 14 project:
Thank you
import { Component, OnInit } from '#angular/core';
import { SeriesColumnOptions, SeriesLineOptions } from 'highcharts';
import * as Highcharts from 'highcharts';
#Component({
selector: 'app-format',
template: '<highcharts-chart [Highcharts]="Highcharts" [options]="options" style="width: 100%; height: 400px; display: block;"></highcharts-chart>'
})
export class FormatComponent implements OnInit {
Highcharts = Highcharts;
options!: Highcharts.Options;
constructor() {
}
ngOnInit(): void {
this.options = {
title: {
text: ''
},
xAxis: {
title: {
text: 'xAxis'
},
categories: ['Cat A', 'Cat B', 'Cat C', 'Cat D', 'Cat E']
},
yAxis: [
{
title: {
text: 'currency axis'
}
},
{
title: {
text: 'percent axis'
},
opposite: true
}
],
series: []
};
const currencySeries: SeriesColumnOptions = {
type: 'column',
name: 'Currency',
data: [123.45, 4324.12, 17245.23, 123.5, 13453.4],
dataLabels: {
enabled: true
},
tooltip: {
valuePrefix: '£',
valueDecimals: 2
}
};
this.options.series?.push(currencySeries);
const percentSeries: SeriesLineOptions = {
type: 'line',
name: 'Percent',
data: [34.1, 62, 82.3, 76.6, 12.3, 99],
yAxis: 1,
dataLabels: {
enabled: true
},
tooltip: {
valueSuffix: '%',
valueDecimals: 1
}
};
this.options.series?.push(percentSeries);
}
}
To format axis labels check xAxis.labels.format, datalabels units or custom formating you can set in dataLabels.format, also recomended options is use callback formatter().
"This" depending on where it is called, refers to an axis or a series.
Highcharts.chart('container', {
xAxis: {
labels: {
formatter: function() {
let label = this.axis.defaultLabelFormatter.call(this);
console.log('xAxis this:', this);
return label;
}
}
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, ],
pointStart: 9000,
type: 'column',
dataLabels: {
enabled: true,
formatter: function() {
console.log('datalabels this:', this);
return this.y;
}
}
}]
});
Demo: https://jsfiddle.net/BlackLabel/vam2t5hw/

React Highcharts not Updating

import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
import React, { useState } from 'react'
const BarChart = () => {
const API = process.env.REACT_APP_API_URL;
var optionsInitial: Highcharts.Options = {
chart: {
type: 'bar'
},
title: {
text: 'Historic World Population by Region'
},
subtitle: {
text: 'Source: Wikipedia.org'
},
xAxis: {
categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania'],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Population (millions)',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' millions'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 80,
floating: true,
borderWidth: 1,
backgroundColor:
'#FFFFFF',
shadow: true
},
credits: {
enabled: false
},
series: [{
type: "bar",
name: 'Year 1800',
data: [107, 31, 635, 203, 2]
}, {
type: "bar",
name: 'Year 1900',
data: [133, 156, 947, 408, 6]
}, {
type: "bar",
name: 'Year 2000',
data: [814, 841, 3714, 727, 31]
}, {
type: "bar",
name: 'Year 2016',
data: [1216, 1001, 4436, 738, 40]
}]
}
const [options, setOptions] = useState<Highcharts.Options>(optionsInitial)
React.useEffect(() => {
fetch(`${API}Clientcomparison/GetSentiment`, {
method: "GET",
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("#token"),
'Content-Type': 'application/json'
}
})
.then((res) => {
return res.json()
})
.then((res : Array<object>) => {
debugger
let optToUpdate = optionsInitial;
let seriesToUpdate: any[] = [];
res.forEach((i:any)=>{
seriesToUpdate = seriesToUpdate.concat([
{
type: "bar",
name: i.categorycount,
data: [814, 841, 3714, 727, 31]
}
])
})
optToUpdate["series"] = seriesToUpdate
setOptions(optToUpdate)
console.log(res)
})
.catch((err) => console.log(err))
}, []);
return (
<HighchartsReact
highcharts={Highcharts}
options={options}
/>
)
}
export default BarChart;
I have tried multiple solutions but not working.
I tried
updateArgs={[true, true, true]}
allowChartUpdate={true}
oneToOne={true}
but no luck.
I am rendering chart first time with hard coded data, then sending API call to fetch data in useEffect and updating the state. I can see in debug tool that state is updated but it is not reflecting.

"viewFullscreen" menu item is not showing in the context menu of highcharts 6.2.0

I have a highchart line chart which currently displayed in bootstrap 4 card.
I want it to displayed full screen, which I'm currently aware that highchart 6.2.0 has option to enabled exporting file, so that I can use the exporting context menu. so, I enabled them but "showFullscreen" option not showing in the exporting context menu.
I imported highchart and exporting module to the component.
in the documentation highchart guys says that I have to include viewFullscreen as string to the menuItems array. I also did that. but nothing work.
import { chart } from 'highcharts';
import * as Highcharts from 'highcharts/highcharts';
import * as HighchartsMore from 'highcharts/highcharts-more';
import * as HighchartsSolidGauge from 'highcharts/modules/solid-gauge';
import * as HighChartExport from 'highcharts/modules/exporting';
HighchartsMore(Highcharts);
HighchartsSolidGauge(Highcharts);
HighChartExport(Highcharts);
#Component({
selector: 'app-line-chart',
templateUrl: './line-chart.component.html',
styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit, OnChanges {
#ViewChild('chartTarget') chartTarget: ElementRef;
#Input() data;
#Input() lineColor;
options: any;
chart: Highcharts.ChartObject;
constructor() { }
ngOnInit() {
this.drawLineChart();
}
ngOnChanges(changes: SimpleChanges) {
if (this.chart && changes['data']) {
this.drawLineChart();
}
}
drawLineChart() {
this.options = {
chart: {
scrollablePlotArea: {
minWidth: 700
},
height: 230,
zoomType: 'x'
},
title: {
text: ''
},
credits: {
enabled: false
},
xAxis: {
gridLineWidth: 1,
/*tickInterval: 7 * 24 * 3600 * 1000, // one week
tickWidth: 0,*/
labels: {
align: 'left',
x: 3,
y: -3,
enabled: false
}
},
yAxis: [{ // left y axis
title: {
text: null
},
padding: 3,
showFirstLabel: false,
gridLineWidth: 1,
/*labels: {
align: 'left',
x: -10
}*/
}],
colors: this.lineColor,
legend: {
align: 'left',
verticalAlign: 'bottom',
borderWidth: 0
},
tooltip: {
shared: true,
crosshairs: true,
headerFormat: ''
},
exporting: {
enabled: true,
menuItemDefinitions: {
// Custom definition
},
buttons: {
contextButton: {
menuItems: ['viewFullscreen']
}
}
},
plotOptions: {
series: {
cursor: 'pointer',
marker: {
enabled: false
}
}
},
series: this.data
};
this.chart = chart(this.chartTarget.nativeElement, this.options as any);
}
}
I followed this link https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/exporting/menuitemdefinitions/
but when I clicked that hamburger icon every other options showing except "viewFullscreen" option didn't work.
To add a custom button to context menu you have to add it to exporting.menuItemDefinitions and also exporting.buttons.contextButton.menuItems array. Note, that fullscreen requires an additional module to be loaded: modules/full-screen.
Code:
Highcharts.chart('container', {
exporting: {
menuItemDefinitions: {
fullscreen: {
onclick: function() {
Highcharts.FullScreen.prototype.init(this.renderTo);
},
text: 'Full screen'
}
},
buttons: {
contextButton: {
menuItems: ['downloadPNG', 'downloadSVG', 'separator', 'fullscreen']
}
}
},
series: [{
data: [
43934,
52503,
57177,
69658,
97031,
119931,
137133,
154175
]
}],
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/full-screen.js"></script>
<div id="container"></div>
Demo:
https://jsfiddle.net/BlackLabel/qydgxs12/
Angular demo:
https://codesandbox.io/s/73lomvnqk0
API reference:
https://api.highcharts.com/highcharts/exporting.buttons.contextButton.menuItems
https://api.highcharts.com/highcharts/exporting.menuItemDefinitions

Highcharts - how to do a responsive pie chart when the texts of the labels are long

I need to do a responsive pie chart with a drilldown on the green area. The text of the labels are too long so in mobile devices it appears like this:
As you can see the texts are cut.
How can I make these texts appear fully in responsive. Please find code below. TIA
Highcharts.chart('recoveryGraf', {
chart: {
type: 'pie'
},
title: {
text: ''
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{point.name}: {point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Brands',
colorByPoint: true,
colors: ['#005eb8','#56b6cc','#8bc540'],
data: [{
name: 'Potential for further recovery',
y: 6,
drilldown: null
}, {
name: 'Non-recoverable<br>(e.g. tissue,wallpaper,etc)',
y: 22,
drilldown: null
}, {
name: 'Recycled',
y: 72,
drilldown: 'Recycleds'
}]
}],
drilldown: {
series: [{
name: 'Recycleds',
id: 'Recycleds',
colors: ['#57a133','#8bc540'],
data: [
['Exported', 16],
['Used Europe', 84]
]
}]
}
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/drilldown.js"></script>
<div id="recoveryGraf"></div>
...
responsive: {
rules: [{
condition: {
maxWidth: 300
},
chartOptions: {
plotOptions: {
pie: {
dataLabels: {
enabled: false
// add your costume code here
}
}
}
}
}]
}

Highstock, dynamically changing from percent stacking to normal stacking

Like the title says, if you have a chart with percent stacking enabled for each series and then try to change to normal stacking using the series.update() method it does not work. It doesn't seem to do anything.
percent to normal example: http://jsfiddle.net/8tbPD/
The reverse does work though.
normal to percent example: http://jsfiddle.net/Tn3n9/
Is there something I'm missing?
Thanks.
$('button').on('click', function() {
for(var index in chart.series) {
chart.series[index].update({stacking:'normal'});
}
});
Unfortunately you need to destroy and create a new chart.
Check this answer on another forum: http://forum.highcharts.com/highstock-usage/dynamic-update-toggle-between-value-and-percentage-t31298/
Basically, add a series with "stacking" but with no data. Then show and hide that series (whose stacking-attribute will affect all other series) using JavaScript, e.g. button.
$(function() {
$('#container').highcharts({
chart: {
type: 'area'
},
title: {
text: 'Historic and Estimated Worldwide Population Distribution by Region'
},
subtitle: {
text: 'Source: Wikipedia.org'
},
xAxis: {
categories: ['1750', '1800', '1850', '1900', '1950', '1999', '2050'],
tickmarkPlacement: 'on',
title: {
enabled: false
}
},
yAxis: {
title: {
text: 'Percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.percentage:.1f}%</b> ({point.y:,.0f} millions)<br/>',
shared: true
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#ffffff',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#ffffff'
}
}
},
series: [{
name: 'Asia',
data: [502, 635, 809, 947, 1402, 3634, 5268]
}, {
name: 'Africa',
data: [106, 107, 111, 133, 221, 767, 1766]
}, {
name: 'Europe',
data: [163, 203, 276, 408, 547, 729, 628]
}, {
name: 'America',
data: [18, 31, 54, 156, 339, 818, 1201]
}, {
name: 'Oceania',
data: [2, 2, 2, 6, 13, 30, 46]
}, {
showInLegend: false,
stacking: 'percent'
}]
});
// the button action
var chart = $('#container').highcharts(),
$button = $('#button');
$button.click(function() {
var series = chart.series[5];
if (series.visible) {
series.hide();
$button.html('Percent');
} else {
series.show();
$button.html('Normal');
}
});
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//code.highcharts.com/highcharts.js"></script>
<script src="//code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 800px; margin: 0 auto"></div>
<button id="button">Normal</button>

Resources