Highcharts not showing string value - javascript

I'm trying to add localstorage values into highchart series but it doesn't work.
When i print the "newString" value on the console and replace the value for "newString" at the code it works but it doesn't when I use var newString.
Here is the code:
$(document).ready(function () {
var archive,
j = "",
keys = Object.keys(localStorage),
x = keys.length;
var i = 0;
while (i < x) {
archive = JSON.parse(localStorage.getItem(keys[i]));
j += "{ name: " + keys[i] + ", data: [" + archive.username + ", " + archive.email + ", " + archive.password + "]},";
i++;
}
var newString = j.substr(0, j.length - 1);
console.log('newString: ', newString);
Highcharts.chart('container', {
title: {
text: 'Datos ingresados'
},
subtitle: {
text: 'Localstorage'
},
yAxis: {
title: {
text: 'Datos ingresados'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2017
}
},
series: [
newString
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
});
This is what console.log shows:
{ name: 2, data: [12345, 23456, 34567]},{ name: 3, data: [23456, 34567, 45678]},{ name: 4, data: [34567, 45678, 56789]},{ name: 5, data: [45678, 56789, 67890]}
When I change the value of newString for that, it works properly.

Because in the second case, Highcharts see your data as a pure string. So, you need to parse your string.
But first of all, we should create valid json for parsing correctly:
var newString = "{ name: 2, data: [12345, 23456, 34567]}"; //bad json
var json = newString.replace(/(['"])?([a-zA-Z0-9]+)(['"])?:/g, '"$2":');
var goodJson = "[" + json + "]"; //valid json
Now we can create options for the Highcharts:
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: []
};
And push data to series as follows:
$.each(JSON.parse(goodJson), function(i, item) {
options.series.push({
name: item.name,
data: item.data
});
});
And finally initialize Highcharts:
var chart = new Highcharts.Chart(options);
See at Plunker

Related

Highcharts data value from variable array string

Got a column called ChartData in database with a string value of 4,11,25,36,50. Trying to assign this value to a hidden variable so JS can read the value of this and put this value in the data option using high charts. I have console.log the variable and looks like its appearing as a string rather than an array when being parsed across the server side to the client side.
C# code
string str = reader["ChartData"].ToString();
string[] strList = str.Split(','); //seperate the hobbies by comma
// convert it in json
dataStr = JsonConvert.SerializeObject(strList, Formatting.None);
hiddenvariable.Value = dataStr;
JS code:
function CreateBoxPlot() {
var hv = $('#hiddenvariable').val();
alert(hv); //["40","61","65","74","77"]
var chart;
var titleText = 'Test Chart Title';
var subTitleText = 'Test Chart Subtitle';
var type = 'boxplot';
var data = hv;
console.log(data); //["40","61","65","74","77"]
$(function () {
$('#container').highcharts({
chart: { type: type, inverted: true },
title: { text: titleText },
subtitle: { text: subTitleText },
legend: { enabled: false },
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({ data: data });
});
}
However when i hardcode data to the below value this works. How do i format this correctly when its parsed over to the JS side:
var data = [[40,61,65,74,77]]
You have to convert the string '["40","61","65","74","77"]' to js array with numbers. To make it work on each browser you can follow this approach:
Parse the string to js array using JSON.parse()
Loop through the created array and convert each element to number:
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
Code:
$(function() {
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
$('#container').highcharts({
chart: {
inverted: true
},
legend: {
enabled: false
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({
data: data
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
Demo:
https://jsfiddle.net/BlackLabel/ay1xmgoc/
Taking reference from the comments, add this to your code and then try.
var data = hv.map(function (element) {
return +element;
});

Shows a single chart on Highcharts

Hello I'm having a problem with my code in Highcharts I already declared my series but it only shows 1 set of chart. All data were set on var dataStr, on how the data that being put, I use push on every data that is being passed. So I think the problem is the with my push?
var dataStr = [
{name: 'JOB-182', problemReportCount: 0, totalCost: 50000, lostHour: 0, lostValue: 0},
{name: 'JOB-185', problemReportCount: 0, totalCost: 3432.65, lostHour: 0, lostValue: 0},
{name: 'JOB-188', problemReportCount: 4, totalCost: 5000, lostHour: 0, lostValue: 0},
{name: 'JOB-189', problemReportCount: 0, totalCost: 1000, lostHour: 0, lostValue: 0}
];
var jRefs = [];
var prJRefs = [];
var prLostVals = [];
var prLostHours = [];
var totCosts = [];
for (var i = 0; i < dataStr.length; i++) {
var jName = '' + dataStr[i].name;
if (jName != '') {
jRefs.push(jName);
var prCount = dataStr[i].problemReportCount;
if (prCount > 0) {
prJRefs.push(jName);
prLostVals.push(dataStr[i].lostValue);
prLostHours.push(dataStr[i].lostHour);
totCosts.push(dataStr[i].totalCost);
}
}
}
var genGraph = function() {
$("#backButton").hide();
$('#prGraph4').highcharts({
chart: {
type: 'column',
plotBackgroundColor: '#F7F7F7'
},
title: {
text: 'Problem Report'
},
subtitle: {
text: 'Estimated Lost Values'
},
xAxis: {
alternateGridColor: '#fff',
categories: prJRefs
},
yAxis: {
min: 0,
title: {
text: 'Amount'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold'
}
}
},
plotOptions: {
column: {
stacking: 'normal',
}
},
tooltip: {
shared: true,
formatter: function() {
var s = '<b>' + this.x + '</b>';
$.each(this.points, function() {
var lostValue = this.y;
s += '<br/><span style=" + dbl + "color:' + this.series.color + ';" + dbl + ">\u25CF</span> ' + this.series.name + ': <b>£</b> ' + lostValue.toFixed(2);
});
return s;
}
},
series:[{
name: 'Total Costs',
data: totCosts,
color: '#2ecc71',
stack: 'total'
}, {
name: 'Estimated Lost Materials Value',
data: prLostVals,
color: '#e74c3c',
stack: 'lost'
}, {
name: 'Estimated Lost Hours Price',
data: prLostHours,
color: '#e67e22',
stack: 'lost'
}]
});
};
Any help would be so much appreciated. Thanks!
You have only one visible column because only one set of data fulfills this condition:
if (prCount > 0) {
prJRefs.push(jName);
prLostVals.push(dataStr[i].lostValue);
prLostHours.push(dataStr[i].lostHour);
totCosts.push(dataStr[i].totalCost);
}
In addition, all values from series: Estimated Lost Materials Value and Estimated Lost Hours Price are 0.
Live demo: http://jsfiddle.net/BlackLabel/vu9ahfk5/

Highcharts - Sunburst Module - series.data : Same var but one work, the other one not

I'm struggling with a very strange problem using Highcharts Sunburst.
Before all, keep in mind that I've validate my JSON and test it in the JSFiddle demo (find in the documentation), everything works fine.
Here's my problem :
I get my data like that :
var data = sessionStorage.getItem('data_fap');
var parsed_data = JSON.parse(data);
var chart_data = parsed_data.data;
( My JSON look like : {data: [{id: "0", parent: "", name: " ", desc: " ", value: " "},...]} )
If a used chart_data in the chart constructor, no chart, no error.
If I set my var this way :
var data = [{id: "0", parent: "", name: " ", desc: " ", value: " "},...]};
And use it in the chart constructor, everything works fine.
I was thinking it could come from my graph options so I copy/paste the one from JSFiddle, still not working...
Here's my complete chart generation code :
var data = sessionStorage.getItem('data_fap');
var parsed_data = JSON.parse(data);
var new_data = parsed_data.data;
// Splice in transparent for the center circle
Highcharts.getOptions().colors.splice(0, 0, 'transparent');
Highcharts.chart('graph_metier', {
chart: {
height: '100%'
},
title: {
text: 'Domaines et familles professionnels'
},
subtitle: {
text: ''
},
series: [{
type: "sunburst",
data: new_data,
allowDrillToNode: true,
cursor: 'pointer',
dataLabels: {
format: '{point.name}',
filter: {
property: 'innerArcLength',
operator: '>',
value: 16
}
},
levels: [{
level: 1,
levelIsConstant: false,
levelSize: {
unit: 'percentage',
value: 30
}
},{
level: 2,
colorByPoint: true
},
{
level: 3,
colorByPoint: true
}]
}],
plotOptions: {
series: {
events: {
click: function (event) {
if(event.point.parent != "0"){
}
}
}
}
},
tooltip: {
formatter: function(e){
if(e.chart.hoverPoint.options.id == 0){
return false;
}
else
{
return '<b>' + e.chart.hoverPoint.options.name + '</b> (code: ' + e.chart.hoverPoint.options.id + ')<br>' + e.chart.hoverPoint.options.desc;
}
}
}
});
If anyone could help me to understand this mess, I'll be infinitely grateful :)

incorrect callback function string

I am using this code belong to plot currency change values but there is a problem while plotting chart.
$(document).ready(function () {
localhost1 = {}; //our global namespace variable
localhost1.chg_percent = [];
localhost1.currency =[];
localhost1.chart1 = {yAxisMin : null, yAxisMax : null }; //this object holds things belonging to this chart1
var url1 = 'http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json&view=basic';
$.ajax({
url: url1,
cache: false,
dataType: 'jsonp',
context: localhost1,
success: function(data) {
for(var i=0; i<data.list.resources.length; i++) {
this.currencyObj = data.list.resources[i].fields;
this.chg_percent.push(parseFloat(data.list.resources[i].resource.fields.chg_percent));
this.currency.push(data.list.resources[i].resource.fields.name);
}
this.chart1.yAxisMax = (function(array){
var number_array = [];
for(var i=0; i<array; i++){
if(array[i] != null){
number_array.push(array[i]);
}
}
return math.max.apply(Math, number_array);
})(this.chg_percent);
this.chart1.yAxisMin = (function(array){
var number_array = [];
for(var i=0; i<array; i++){
if(array[i] != null){
number_array.push(array[i]);
}
}
return math.min.apply(Math, number_array);
})(this.chg_percent);
this.chart1.data.series[0].data = this.chg_percent;
this.chart1.data.xAxis.categories = this.currency;
chart = new Highcharts.Chart(this.chart1.data);
console.log(data);
}
});
localhost1.chart1.data = {
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Historic World Population by Region'
},
subtitle: {
text: 'Source: Source : yahoo'
},
xAxis: {
categories: null,
title: {
text: null
}
},
yAxis: {
min: localhost1.chart1.yAxisMin,
max: localhost1.chart1.yAxisMax,
title: {
text: 'Daily Percentage Change',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
formatter: function(){
return ''+
this.series.name +': '+ this.y +' %';
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -1,
y: 1,
floating: true,
borderWidth: 1,
backgroundColor: '#FFFFFF',
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'Daily Change',
data: null
}]
};
});
when i run this code, i get an error message in console "Not acceptable : http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json&view=basic&callback=jQuery18203581249208157574_1452451202663&_=1452451202773".
though the api i have used is correct but the string that callback function returns seems to be incorrect.

Unable to plot data json data on highcharts

I am trying to load json data to high-charts. I am receiving json data from DB using $.getJSON function. Here is my sample json that i am receiving from DB,
My sample json
[
{
"target":"collectd.matrix.oracle.avg_resp_time","datapoints":[[8.0, 1365158480],[null, 1365158490],[null, 1365158500],[null, 1365158510],[null, 1365158520],[null,1365158530],[8.0, 1365158540],[null, 1365158550],[null, 1365158560],[null, 1365158570],[null, 1365158580],[null, 1365158590]]
}
]
$.getJSON("myURL", createOrderDurationChart);
On success response from $.getJSON i call function below,
I am using scala framework.
I am not getting what is wrong in code or json. I can plot this json by embedding code in simple javascript and run through html directly as sample.
Here is the sample code,
function createOrderDurationChart(durationMap){
//var target=durationMap[0].target;
//var jsonstr=durationMap[0].datapoints;
//alert(target);
//alert(jsonstr);
var orderDurationChart = new Highcharts.Chart({
chart: {
renderTo: "order_duration_div",
type: "column",
margin: [10, null, null, null],
//marginRight: 10,
zoomType: 'xy',
},
title: {
text: "order duration"
//y: 5
},
xAxis: {
type: "datetime",
//tickInterval: 60*1000*10
},
yAxis: {
title: {
text: "seconds"
},
startOnTick : false,
endOnTick: false
},
series: [{
name:"avg",
data: (function (){
var data = [], i;
var jsondata = [];
jsondata= durationMap[0].datapoints;
alert(jsondata)
var datapoints=JSON.parse(jsondata);
// var jsonstr=parsejson[0].datapoints;
console.log('jsotn ' + datapoints);
// var mydata = JSON.parse(jsonstr);
// alert(mydata);
// datapoints = mydata[0].datapoints;
//alert("initial:" + json[0].time + ':' + json[0].value);
for (i = 0; i < datapoints.length; i++) {
data.push({
x:datapoints[i][1],
y:datapoints[i][0]
});
console.log('x: ' + datapoints[i][1] + ', y: ' + datapoints[i][0]);
}
return data;
})
()}]
});
}
Update code after json fix,
function createOrderDurationChart(durationMap){
//var target=durationMap[0].target;
//var jsonstr=durationMap[0].datapoints;
//alert(target);
//alert(jsonstr);
var orderDurationChart = new Highcharts.Chart({
chart: {
renderTo: "order_duration_div",
type: "column",
margin: [10, null, null, null],
//marginRight: 10,
zoomType: 'xy',
},
title: {
text: "order duration"
//y: 5
},
xAxis: {
type: "datetime",
//tickInterval: 60*1000*10
},
yAxis: {
title: {
text: "seconds"
},
startOnTick : false,
endOnTick: false
},
series: [{
name:"avg",
data: (function (){
var data = [], i;
var jsondata = [];
datapoints= durationMap[0].datapoints;
console.log('jsotn ' + datapoints);
for (i = 0; i < datapoints.length; i++) {
data.push({
x:datapoints[i][1],
y:datapoints[i][0]
});
console.log('x: ' + datapoints[i][1] + ', y: ' + datapoints[i][0]);
}
return data;
})
()}]
});
}
Any suggestions most welcome.
Thanks

Categories

Resources