Creating Highchart Graph with JavaScript - javascript

I want to create high chart graph .
Here is FIDDLE LINK of My code.
I am giving two values a and b . a for x-axis b for y-axis. Problem is that when i gave values of a and b . when the difference between a and b is less, then no graph appears
i-e. a= -9 , b= -9 . Otherwise it works
$(function () {
var a, b, x, j;
a = -9;
b = -9;
if (a > b) {
x = a;
j = b
} else {
x = b;
j = a
}
alert("X is " + x);
alert("Y is" + j);
$('#container').highcharts({
chart: {
type: 'bar',
backgroundColor: null
},
credits: {
enabled: false
},
tooltip: {
enabled: false,
},
title: {
text: ''
},
xAxis: {
categories: ["", "", ""],
//minTickInterval:20000,
},
yAxis: {
min: j - (j * 5 / 100),
max: x + (x * 5 / 100),
//min: -50,
//max: -50,
//minTickInterval:20000,
endOnTick: true,
tickPixelInterval: 340,
maxPadding: 0.25,
title: {
text: ''
},
labels: {
formatter: function () {
if (j - (j * 5 / 100) > 1000000) {
return Highcharts.numberFormat((this.value) / 1000000, 0, '', ',') + 'M';
} else if (j - (j * 5 / 100) > 1000) {
return Highcharts.numberFormat((this.value) / 1000, 0, '', ',') + 'K';
} else {
return Highcharts.numberFormat((this.value), 0, '', ',');
}
},
x: 6
}
},
legend: {
backgroundColor: '#FFFFFF',
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: ' ',
data: [a]
},
{
name: ' ',
data: [0, b]
}, ]
});
});

Here's a working fiddle
Just remove:
min: j-(j*5/100),
max: x+(x*5/100)
from the yAxis: { --- some options --- }
Also try this with one value positive and other negative for a and b.
Hope this helps.

Related

Plotline (vertical line) in highcharts scatter chart

https://jsfiddle.net/7zL0v5oq/
I would like to have a plotline at today's date. The list can get quite long and in that case it helps with having an oversight. I fear it doesn't work because it is a scatter chart but I don't know what the problem is. I've searched all over the place but everything leads to plotlines, which clearly doesn't work. I would also be thankful if anyone knew, whether there was an easy way to filter my data the way I have it (standard highcharts filtering is deactivated but doesn't really help because of the static y values, so I get a huge, white space in the middle unless I filter at the edges. Thank you in advance for your help.
data = [{
"id": 1,
"release": "Software1",
"routine_failure_analysis_ended_on": null,
"sw_maintenance_releases_ended_on": "2014-04-01",
"sale_ended_on": "2013-04-01",
"security_vul_support_ended_on": "2015-04-01",
"service_contract_renewal_ended_on": null,
"svc_attach_ended_on": null,
"support_ended_on": "2018-03-31",
"updated_dates_on": "2012-10-03",
"created_at": "2018-05-04T18:53:21.301+02:00",
"updated_at": "2018-05-16T08:36:24.940+02:00"
},
{
"id": 2,
"release": "Software2",
"routine_failure_analysis_ended_on": null,
"sw_maintenance_releases_ended_on": "2019-07-24",
"sale_ended_on": "2017-07-31",
"security_vul_support_ended_on": "2020-07-24",
"service_contract_renewal_ended_on": null,
"svc_attach_ended_on": null,
"support_ended_on": "2022-07-31",
"updated_dates_on": "2015-08-14",
"created_at": "2018-05-05T04:00:44.170+02:00",
"updated_at": "2018-05-16T08:36:29.325+02:00"
},
{
"id": 3,
"release": "Software3",
"routine_failure_analysis_ended_on": null,
"sw_maintenance_releases_ended_on": "2018-03-01",
"sale_ended_on": "2017-03-01",
"security_vul_support_ended_on": "2018-12-01",
"service_contract_renewal_ended_on": null,
"svc_attach_ended_on": null,
"support_ended_on": "2022-02-28",
"updated_dates_on": "2016-09-02",
"created_at": "2018-05-05T04:00:44.401+02:00",
"updated_at": "2018-05-16T08:36:31.643+02:00"
}
];
const colors = ["#516", "#1781e3", "#25b252", "#20c997", "#ffc107", "#ff8b2e", "#dd1122"];
//Change to store y value paired to release/pid
var change = {};
//Which y values need to be displayed
var ticks = [0];
//Description of events
var sale = "Sale";
var support = "Support";
var svc = " SVC attach";
var sw = "Software maintenance";
var routine = "Routine failure analysis";
var service = "Service contract renewal";
var security = "Security vulnerability support";
//Data array for series
var high = [];
data.sort(function(a, b) {
return Date.parse(a.support_ended_on) < Date.parse(b.support_ended_on) ? 1 : -1
})
for (var i = 0; i < data.length; i++) {
var arr = [{
x: Date.parse(data[i].sale_ended_on),
y: (i + 1) * 20,
color: colors[0],
myValue: sale
},
{
x: Date.parse(data[i].sw_maintenance_releases_ended_on),
y: (i + 1) * 20,
color: colors[1],
myValue: sw
},
{
x: Date.parse(data[i].security_vul_support_ended_on),
y: (i + 1) * 20,
color: colors[2],
myValue: security
},
{
x: Date.parse(data[i].svc_attach_ended_on),
y: (i + 1) * 20,
color: colors[3],
myValue: svc
},
{
x: Date.parse(data[i].routine_failure_analysis_ended_on),
y: (i + 1) * 20,
color: colors[4],
myValue: routine
},
{
x: Date.parse(data[i].service_contract_renewal_ended_on),
y: (i + 1) * 20,
color: colors[5],
myValue: service
},
{
x: Date.parse(data[i].support_ended_on),
y: (i + 1) * 20,
color: colors[6],
myValue: support
}
];
var key, value;
line = [{
x: Date.parse(data[i].sale_ended_on),
y: (i + 1) * 20
}, {
x: Date.parse(data[i].support_ended_on),
y: (i + 1) * 20
}]
//Adding to change list, so we can add release/pid as label to y axis
key = (i + 1) * 20;
ticks.push(key);
if (data[i].pid) {
value = data[i].pid;
} else {
value = data[i].release;
}
change[key] = value;
//Expanding high (which is used for the highcharts series) with arr (all points for one pid)
if (data[i].pid) {
high.push({
label: data[i].pid,
name: data[i].pid,
type: 'scatter',
data: arr
}, {
type: 'line',
data: line,
linkedTo: ":previous"
});
} else {
high.push({
label: data[i].release,
name: data[i].release,
type: 'scatter',
data: arr,
showInLegend: false
}, {
type: 'line',
data: line,
linkedTo: ":previous"
});
}
}
Highcharts.chart("container", {
chart: {
height: data.length * 75
},
credits: {
enabled: false
},
yAxis: {
title: {
text: null
},
tickPositions: ticks,
visible: true,
labels: {
formatter: function() {
var value = change[this.value];
return value !== 'undefined' ? value : this.value;
}
}
},
xAxis: {
plotlines: [{
color: "#dd1122",
width: 2,
value: +new Date()
}],
type: 'datetime',
},
plotOptions: {
scatter: {
marker: {
symbol: 'circle',
radius: 7,
lineWidth: 2
}
},
line: {
enableMouseTracking: false,
marker: {
enabled: false
},
color: '#bbb',
lineWidth: 3
}
},
tooltip: {
formatter: function() {
var str = '<b>' + this.series.name + '</b><br/>'
if (this.point.myValue) {
str += this.point.myValue;
} else {
str += "Corrupted data!";
}
if (this.point.x < Date.parse(new Date))
return str += " ended on:<br/>" + Highcharts.dateFormat('%e %b %Y', new Date(this.x));
else
return str += " will end on:<br/>" + Highcharts.dateFormat('%e %b %Y', new Date(this.x));
},
shared: false
},
series: high
})
You have a typo, use plotLines instead of plotlines:
xAxis: {
plotLines: [{
...
}],
...
}
Live demo: https://jsfiddle.net/BlackLabel/p3u8ejtb/
API Reference: https://api.highcharts.com/highcharts/xAxis.plotLines

Filter categories in highcharts by using checkboxes

I would like to filter the categories by using the checkboxes. For example, if the user checks Server - only Categories belonging to class Server should be visible and redraw the highchart.
Like this:
And if the user checks all checkboxes, all categories should be visible.
Here is the fiddle: http://jsfiddle.net/Lqcrgrbh/
Thanks in advance!
$(function() {
var chart = new Highcharts.Chart('container', {
chart: {
type: 'columnrange',
inverted: true,
height: 100
},
title: {
text: null
},
xAxis: {
categories: [{"name":"Email","sys_class":"Business Service"},{"name":"Server","sys_class":"Server"}],
labels: {
formatter: function () {
return this.value.name;
},
useHTML: true
}
},
yAxis: {
type: 'datetime',
tickInterval: 1000 * 60 * 60 * 24 * 30 * 6,
title: {
text: null
},
labels: {
formatter: function () {
return Highcharts.dateFormat('%b %Y', this.value);
}
}
},
plotOptions: {
series: {
grouping: false,
stacking: 'normal',
pointPadding: 0,
groupPadding: 0.0,
allowPointSelect: true,
dataLabels: {
enabled: true,
align: 'center',
x: -10,
formatter: function() {
return this.series.name;
}
}
}
},
tooltip: {
formatter: function() {
var categories = this.x.name,
series_name = this.series.name,
low = this.point.low,
high = this.point.high,
duration = high - low;
return '<b>' +series_name + '</b><br/><b>'+ categories + ': </b>'+ Highcharts.dateFormat('%d %b %Y',
new Date(low)) + " - " + Highcharts.dateFormat('%d %b %Y',
new Date(high)) + '<br/><b>Duration: </b>' + parseInt(duration / (1000 * 60 * 60 * 24 * 365)) + " years, " + new Date(duration).getUTCMonth() + " months, " + new Date(duration).getUTCDate() + " days";
}
},
legend: {
enabled: false
},
series: [{"color":"#f47700","data":[[],[1475539200000,1570147200000]],"name":"Concept"},{"color":"#f43701","data":[[1475625600000,1570233600000],[]],"name":"Planing"}]
});
});
You should be able to edit your togglePointsByClass method so you will not hide your series, but you will change extremes on your xAxis. In this case you can use Axis.update() method.
function togglePointsByClass(className, shouldShow, chart) {
var isChartDirty = false;
if (shouldShow) {
chart.xAxis[0].userOptions.categories.forEach(function(category, i) {
if (category.class === className) {
visibleArr.push(i);
}
});
} else {
chart.xAxis[0].userOptions.categories.forEach(function(category, i) {
if (category.class === className && visibleArr.indexOf(i) > -1) {
visibleArr.splice(visibleArr.indexOf(i), 1);
}
});
}
if (visibleArr.length) {
chart.xAxis[0].update({
min: Math.min.apply(null, visibleArr),
max: Math.max.apply(null, visibleArr)
})
}
}
Here you can see simple example how it can work: http://jsfiddle.net/Lqcrgrbh/1/

Highcharts Line Charts Out of memory

I am trying to populate a line chart using Highcharts. It was working great until a couple of days ago, then it started crashing Chrome and Internet Explorer gives the "SCRIPT7: Out of memory" error. I have 3 other line charts built the exact same way, that work fine. This chart works great as a column chart.
Here is the JSFIDDLE. Code below:
function average(arr) {
return _.reduce(arr, function(memo, num) {
var total = memo + num;
return memo + num;
}, 0) / (arr.length === 0 ? 1 : arr.length);
}
function translateMonth(d) {
var month;
if (d.getMonth() === 0) {
month = 'Jan';
} else if (d.getMonth() === 1) {
month = 'Feb';
} else if (d.getMonth() === 2) {
month = 'Mar';
} else if (d.getMonth() === 3) {
month = 'Apr';
} else if (d.getMonth() === 4) {
month = 'May';
} else if (d.getMonth() === 5) {
month = 'Jun';
} else if (d.getMonth() === 6) {
month = 'Jul';
} else if (d.getMonth() === 7) {
month = 'Aug';
} else if (d.getMonth() === 8) {
month = 'Sep';
} else if (d.getMonth() === 9) {
month = 'Oct';
} else if (d.getMonth() === 10) {
month = 'Nov';
} else if (d.getMonth() === 11) {
month = 'Dec';
}
return month;
}
var npsData = [];
npsData = [{
avg: 100,
coach: "NUNES",
date: "Jul"
},{
avg: 100,
coach: "NUNES",
date: "Jul"
},{
avg: 100,
coach: "NUNES",
date: "Jul"
},{
avg: 100,
coach: "NUNES",
date: "Jul"
},{
avg: 100,
coach: "NUNES",
date: "Aug"
},{
avg: 100,
coach: "NUNES",
date: "Aug"
}]
var npsChartData = [];
npsChartData = _.chain(npsData)
.groupBy("date")
.map(function(value, key) {
return {
name: key,
y: parseFloat(Math.round(average(_.pluck(value, "avg"))))
}
})
.value();
var chart4 = new Highcharts.Chart({
chart: {
type: 'line',
renderTo: 'postCoachingSurvey',
plotBorderColor: '#0574AC',
borderWidth: .5,
plotShadow: true
},
credits: {
enabled: false
},
title: {
text: 'Post Coaching Survey',
style: {
color: '#666666',
fontWeight: 'bold'
}
},
legend: {
enabled: false,
itemStyle: {
color: '#868686',
fontSize: '10px'
}
},
xAxis: {
categories: _.pluck(npsChartData, name),
labels: {
enabled: true,
formatter: function() {
return this.value;
}
}
},
yAxis: {
tickPositioner: function () {
var positions = [],
tick = Math.floor(this.dataMin),
increment = Math.ceil((this.dataMax - this.dataMin) / 6);
for (tick; tick - increment <= this.dataMax; tick += increment) {
positions.push(tick);
}
//console.log (positions);
return positions;
}, title: {
text: 'eNPS',
style: {
color: '#666666'
}
},
labels: {
format: '{value}%'
}
},
tooltip: {
enabled:false,
pointFormat: '{point.y}' + '%',
crosshairs: true
//percentageDecimals: 1
},
plotOptions: {
series: {
cursor: 'pointer',
dataLabels: {
enabled: true,
//formatter: function() {
//return '{point.y}' + '%';
//}
}
}
},
series: [{
type: 'line',
name: 'Nps Average Score',
data: npsChartData,
color: '#EB6E00'
}]
});//end chart4
The particular data for this chart brings out an error in your code. You have an endless loop in your yAxis.tickPositioner function. You have this code:
increment = Math.ceil((this.dataMax - this.dataMin) / 6);
for (tick; tick - increment <= this.dataMax; tick += increment) {
// ...
}
In short, your increment value becomes 0 if the min and max value of the data is the same, and therefore your for loop statement tick += increment does nothing, and it keeps going forever.
This can be fixed by assuring your increment value is a minimum of 1. You could try (JSFiddle):
increment = Math.max(1, Math.ceil((this.dataMax - this.dataMin) / 6));

Restacking cumulative columns in Highcharts marimekko charts

I've got a basic variable width column chart (aka Marimekko) set up using Highcharts but am having trouble getting it to restack the columns properly to eliminate the data gap once a series has been removed or hidden.
JSFIDDLE DEMO <-- I've set up a demo of the issue here.
You'll notice clicking on a legend item removes the series from the chart, but it also removes all of the following data points in the array (i.e. clicking on series C removes series C, D, and E whereas it should redraw to A-B-D-E). Since the y-axis data is meant to display a cumulative sum of all series, these should re-shuffle as adjacent columns with no gaps. How can I get this to render properly?
THIS POST uses similar demo code and attempting to solve the same problem, however the answer is somewhat elusive and I am unable to get it working.
Thanks in advance!
$(function () {
var dataArray = [
{ name: 'A', x: 200, y: 120 },
{ name: 'B', x: 380, y: 101 },
{ name: 'C', x: 450, y: 84 },
{ name: 'D', x: 198, y: 75 },
{ name: 'E', x: 95, y: 55 }
];
function makeSeries(listOfData) {
var sumX = 0.0;
for (var i = 0; i < listOfData.length; i++) {
sumX += listOfData[i].x;
}
var allSeries = []
var x = 0.0;
for (var i = 0; i < listOfData.length; i++) {
var data = listOfData[i];
allSeries[i] = {
name: data.name,
data: [
[x, 0], [x, data.y],
{
x: x + data.x / 2.0,
y: data.y,
dataLabels: { enabled: false, format: data.x + ' x {y}' }
},
[x + data.x, data.y], [x + data.x, 0]
],
w: data.x,
h: data.y
};
x += data.x + 0;
}
return allSeries;
}
$('#container').highcharts({
chart: { type: 'area' },
xAxis: {
tickLength: 0,
labels: { enabled: true}
},
yAxis: {
title: { enabled: false}
},
plotOptions: {
series: {
events: {
legendItemClick: function () {
var pos = this.index;
var sname = this.name;
var chart = $('#container').highcharts();
while(chart.series.length > 0) {
chart.series[pos].remove(true);
}
dataArray[pos]= { name: sname, x: 0, y: 0 };
chart.series[0].setData(dataArray);
}
}
},
area: {
lineWidth: 0,
marker: {
enabled: false,
states: {
hover: { enabled: false }
}
}
}
},
series: makeSeries(dataArray)
});
});

Highcharts : yAxis, values rounded to a maximum of two decimal places

The code of my graph is this (take data from a php page and then adds some series):
$('#grafico_1').highcharts({
chart: {
type: 'line',
zoomType: 'xy',
animation : false,
events: {
selection: function(event) {
if(event.resetSelection){
setTimeout(function(e){
var chart = $('#grafico_1').highcharts();
var extreme = chart.yAxis[0].getExtremes();
var mio_min = parseFloat(proprieta_temperatura_aperto[34]);
var mio_max = parseFloat(proprieta_temperatura_aperto[35]);
if(extreme.dataMin < mio_min){
mio_min = extreme.dataMin;
}
if(extreme.dataMax > mio_max){
mio_max = extreme.dataMax;
}
chart.yAxis[0].setExtremes(mio_min,mio_max);
$("#temperatura_min_max_rilevato").html("Min "+extreme.dataMin+"°C - Max "+extreme.dataMax+"°C");
//console.log("zoom - ");
}, 10);
}else{
setTimeout(function(e){
var chart = $('#grafico_1').highcharts();
var extreme = chart.yAxis[0].getExtremes();
$("#temperatura_min_max_rilevato").html("Min "+extreme.dataMin+"°C - Max "+extreme.dataMax+"°C");
//console.log("zoom + "+JSON.stringify(extreme));
}, 50);
}
}
},
},
credits : {
enabled : false
},
title: {
text: 'Grafico di Oggi'
},
xAxis: {
type: 'datetime',
title: {
text: false
}
},
yAxis: [
{
title: {
text: false
},
labels: {
format: '{value}°C',
},
//ceiling : parseFloat(proprieta_temperatura_aperto[35]),
//floor: parseFloat(proprieta_temperatura_aperto[34]),
max : parseFloat(proprieta_temperatura_aperto[35]),
min: parseFloat(proprieta_temperatura_aperto[34]),
},
{
title: {
text: false
},
min: 0,
max : 1,
ceiling:1,
floor : 0,
//tickLength : 1,
opposite: true,
tickInterval: 1,
labels: {
formatter: function() {
if (this.value == 0 || this.value == 1){
return this.value;
}else{
return null;
}
}
}
}
],
tooltip: {
formatter: function() {
var s = '<b>Data</b> '+Highcharts.dateFormat('%H:%M:%S', this.x) + '<br><b>Temperatura</b> ' + this.y + '°C<br/>';
$.each(this.points, function(i, point) {
if(point.series.name != "Temperatura"){
s += '<b>' + point.series.name +'</b> : '+ point.y + '<br>';
}
});
return s;
},
shared: true,
backgroundColor: '#FCFFC5'
},
plotOptions: {
line : {
turboThreshold: 0,
},
series: {
animation: false,
marker: {
enabled: false
}
}
},
series: []
});
the problem occurs when run one (or more) zoom on the graphs , and on the y-axis the values ​​are listed with more than two decimal places. I would like to limit to two the maximum number of decimal places.
I think i have to change this field (format)
yAxis: [
{
labels: {
format: '{value}°C',
},
but I do not know how.
Try to write the value as {value:.2f}, as proposed here: link

Categories

Resources