Getting error when try to use external parameter to generate chart - javascript

I retrieve JSON data from server and put it in Highchart as series.I am facing this error:
Error: Invalid value for attribute y="NaN" highcharts.js : 9
The error happen if I send chartSeries parameter from callChart function.But if I copy chartSeries value and put it directly inside drawChart it able to display the chart.However there no problem for other parameter such chartCategory and chartTitle.
Here is my code:
function callChart(){
for (var i in jsonData){
console.log('#i '+i);
console.log('#subSegment i '+jsonData[i].subSegment);
var chartTitle= jsonData[i].subSegment;
console.log('categories '+ jsonData[i].categories);
var chartCategory= jsonData[i].categories;
console.log('series '+ JSON.stringify(jsonData[i].series));
var chartSeries=JSON.stringify(jsonData[i].series);
drawChart($('.chartContainer'),chartSeries,chartCategory,chartTitle);
break;}}
Here is the code of drawChart;
function drawChart(container,chartSeries,chartCategory,chartTitle) {
console.log('# test');
console.log('# chartSeries='+chartSeries);
console.log('# chartCategory='+chartCategory);
console.log('# chartTitle='+chartTitle);
//it works if I put the chartSeries directly here
/*chartSeries=[{"type":"column","stack":null,"pointPlacement":null,"name":"HDD","linkedTo":null,"id":"hdd","data":[30,30,70,90,37,200],"color":"greenColor","borderWidth":null},{"type":"column","stack":"old","pointPlacement":null,"name":"SSHD","linkedTo":null,"id":"sshd","data":[0,100,40,90,60,90],"color":"yellowColor","borderWidth":null},{"type":"column","stack":"old","pointPlacement":null,"name":"SSD","linkedTo":null,"id":"ssd","data":[50,100,40,90,60,100],"color":"blueColor","borderWidth":null},{"type":"column","stack":"forecast","pointPlacement":null,"name":"HDD","linkedTo":"hdd","id":null,"data":[30,80,40,100,60,90],"color":"greenColor","borderWidth":null},{"type":"column","stack":"forecast","pointPlacement":null,"name":"SSD","linkedTo":"ssd","id":null,"data":[30,80,40,100,60,90],"color":"yellowCollor","borderWidth":null},{"type":"spline","stack":null,"pointPlacement":null,"name":"Share","linkedTo":null,"id":null,"data":[30,80,40,100,60,90],"color":"black","borderWidth":null}] ;
*/
if (!container.length) {
return;
}
var chart = new Highcharts.Chart({
tooltip: {
enabled: true
},
credits: {
enabled: false
},
chart: {
renderTo: container[0],
style: {
fontFamily: '"Arial", "Helvetica", "sans-serif"',
fontSize: '12px',
fontWeight: 'bold'
},
marginLeft:60,
marginRight:65
},
title: {
text: chartTitle
},
xAxis: {
categories: chartCategory
},
yAxis: [{
min: 0,
title: {
text: 'Units in 000\' s'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
}, { // Secondary yAxis
title: {
text: 'Share',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true,
min: 0,
max: 100
}],
legend: {
enabled:false
},
plotOptions: {
column: {
grouping: false,
stacking: 'normal',
pointWidth:30
},
series:{shadow:false}
}
,series:chartSeries
});
}
Thanks alot.

Okay, I found it already.
Instead pass JSON.stringify(jsonData[i].series) , directly pass jsonData[i].series.
Thanks

Related

not working to update node of network graph

i'm using highchart to draw network graph.
and i want to change node's color.
my code to update node is
highchart.series[0].nodes[5].update({color: '#ff0000'});
it seem to work, but i get error like this.
Uncaught TypeError: Cannot read property 'concat' of undefined
at t.setNodeState [as setState]
i guess it's not working
when i update edge's node(has no "from or to" link) and move mouse on graph.
how i can update node's color?
enter image description here
const graphData = [
{from: 'Root', to: 'Group1'},
{from: 'Group1', to: 'Group1-1'},
{from: 'Group1-1', to: 'file1-1-1'},
{from: 'file1-1-1', to: 'asset1-1-1'},
{from: 'file1-1-1', to: 'asset1-1-2'},
];
const nodeData = [
{ id: 'Root', color: '#000000'},
{ id: 'Group1', color: '#00ff00' },
{ id: 'Group1-1', color: '#00ff00' },
{ id: 'file1-1-1', color: '#0000ff' },
{ id: 'asset1-1-1', color: '#d0d0d0' },
{ id: 'asset1-1-2', color: '#d0d0d0' },
];
const highchart = Highcharts.chart('highchart', {
chart: {
type: 'networkgraph',
plotBorderWidth: 1,
backgroundColor: 'transparent',
},
title: {
text: undefined
},
plotOptions: {
networkgraph: {
keys: ['from', 'to'],
layoutAlgorithm: {
enableSimulation: true,
linkLength: 100,
integration: 'verlet', // "euler"
},
link: {
width: 1,
color: '#B1B1B0',
dashStyle: 'Dash'
},
dataLabels: {
enabled: true,
y: -1,
style: {
fontSize: 10,
fontFamily: 'NotoSans-SemiBold',
textOutline: false
},
inside: false, // text 반전
textPath: {
enabled: false // circle 에 맞춰 text 곡선처리
},
linkTextPath: {
enabled: false
},
linkFormat: '',
},
point: {
events: {
update: function(param){
console.log('update', param)
}
}
}
},
},
tooltip: {
enabled: false
},
series: [{
name: 'Root',
id: 'Root',
allowPointSelect: true,
data: graphData,
nodes: nodeData,
}]
});
$('#btn').on('click', function(){
highchart.series[0].nodes[5].update({marker: {
fillcolor: '#ff0000'
}});
});
#highchart {
width: 500px;
height: 500px;
background: #f0f0f0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/8.2.2/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/networkgraph.js"></script>
<button id="btn">update</button>
<div id="highchart"></div>
The update feature doesn't exist for the nodes. It works for the points - https://api.highcharts.com/class-reference/Highcharts.Point#update
However, you can change the point color in this way:
highchart.series[0].nodes[5].graphic.css({
fill: 'red'
})
Demo: https://jsfiddle.net/BlackLabel/0Lwuce7q/

Issue to add dynamic value in Highcharts jquery

I am facing an issue to add the dynamic value in Highcharts Jquery. I have two arrays like name and value
name/categoryname - ["ZYG", "BLA", "GAS", "LBE", "LIM", "EMB", "NAU"]
value/basevalue - [483.7932253,601.125844,680.2910403,886.7269613,548.3400347,630.8979143,0]
face the issue in passing the base value in. I tried to pass the value in the array and string type. The issue is not solved yet.
I used the bar chart to display. The coding is here. Normally coding works fine. The issue faced when I use dynamic value.
function displaychart(obj)
{
var categoryname = [];
$.each(obj['name'], function( key, value ) {
categoryname.push(value);
});
var ybasevalue = "[";
$.each(obj['basevalue'], function( key, value ) {
ybasevalue += value + ",";
});
ybasevalue += "]";
Highcharts.chart('container'+i, {
chart: {
type: 'bar'
},
title: {
text: 'Protein Sequence'
},
subtitle: {
text: 'Source'
},
xAxis: {
categories: categoryname,
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Proteomics',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ''
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 180,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series:[
{
name: 'Protein',
data: ybasevalue
},
]
});
}
}
I pass an array of Strings instead of an array of Numbers. Values inside single or double quotes are Strings in JavaScript.
So I use
var ybasevalue = [];
$.each(obj[i]['basevalue'], function( key, value ) {
ybasevalue.push(parseInt(value)); });

Draw piechart with highcharts using php array of data

I want to replace PHP array $os_array with JavaScript variable to send with different values. Like as var x =<?php echo $os_array; ?>; drawcharts($x); when alert var x result will be ['Internet Explorer 7',1],['Internet Explorer 8',1],['Outlook 2007',2]
var x="<?php echo $os_array;?>";
drawcharts(x);
function drawcharts(x){
$('#_shared_graphs').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
backgroundColor: '#f1f1f1'
},
title: {
text: 'OS'
},
tooltip: {
pointFormat: '{point.y} Using <b>{point.name}'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Sent Messag stat',
data: [x]
}]
});
}
well just define your js fkt:
function drawcharts(x) {
$('#_shared_graphs').highcharts({
...
series: [{
...
data: x
}]
});
}
then
var x =<?php echo json_encode($os_array); ?>;
drawcharts(x);
// reassign x
x = [ .... ];
drawcharts(x);

How to add multiple series dynamically and update its data dynamically

my task is to add series dynamically and keep updating their data, which is received by ajax calls.
i know series can be added dynamically by declaring highchart funciton global. and using series.addseries() function , and also data can be updated by using settimout request to ajax call and updating points by using series.addpoint() function.
i have done both the work separably. but when i combine both the technique, data is not added to highchart. i have done lot of research on this, and i am not finding reason for not adding the data. infact script hang the browser.
i have checked the series object, which show x-data and y-data are processed. only difference i find is isDirty field and isDirtydata field are set to true. dont know the reason.
here is the full code
var serverUrl = 'http://'+window.location.hostname+':8000'
Highcharts.setOptions({
global: {
useUTC: false
}
});
data={}
$(document).ready(function(){
$(function () {
console.log("highcharts")
$('#first').highcharts({
chart: {
type: 'spline',
//marginRight: 150,
marginBottom: 5,
events: {
load: requestData(data)
}
},
title: {
text: 'Server Monitroting Tool'
},
subtitle: {
text: 'Cpu usage, Memory Usage,Disk Usage,Mongo Usage'
},
xAxis: {
type: 'datetime',
categories: ['TIME'],
dateTimeLabelFormats : {
hour: '%I %p',
minute: '%I:%M %p'
}
},
yAxis:{
showEmpty:false
},
legend:
{
backgroundColor: '#F5F5F5',
layout: 'horizontal',
floating: true,
align: 'left',
verticalAlign: 'bottom',
x: 60,
y: 9,
shadow: false,
border: 0,
borderRadius: 0,
borderWidth: 0
},
series: {}
});
});
from_date=new Date().getTime()-60000;
function requestData(data)
{
if(!data)
{
console.log("default ")
}
else
{
console.log("requesting")
$.ajax({
url:serverUrl+'/api/fetch_params/',
type:'GET',
data:data,
success:function(response)
{
console.log("in success")
//data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
var id=data['sub-type']+data['param']
var series = chart.get(id)
shift = series.data.length > 100; // shift if the series is longer than 300 (drop oldest point)
response= $.parseJSON(response)
var x=data['sub-type']
all_data=response.response.data[x]
// console.log(new Date(from_date),'latest timestamp')
console.log(series)
console.log("data",all_data)
from_date=all_data[all_data.length-1][0]
// console.log(from_date)
// series.isDirty=false
// series.isDirtyData=false
for (var i = 0; i < all_data.length; i++)
{
series.addPoint({ x: all_data[i][0],y: all_data[i][1],id: i},false,shift);
}
console.log("series object",series)
// chart.redraw();
console.log(" parameter",data)
data['from-date']=from_date
console.log("data",series.data)
// console.log(chart)
setTimeout(requestData(data), 10000);
console.log("out of success")
},
cache:false,
error:function()
{
console.log("err")
}
});
}
}
$.ajax({
url:serverUrl+'/api/fetch_all_servers/',
type:'GET',
success:function(response){
response = $.parseJSON(response)
sd = response.response.all_servers
$('input[name=select_menue]').optionTree(sd)
},
error:function(){
console.log('error')
}
});
$('.param-button').live('click',function(e){
e.stopPropagation()
})
$('param-select').live('hover',function(){
$(this).find('.type-select').show()
});
$('.final_value').live('change',function(){
select_name = 'select_menue_'
param_list = []
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
while(param){
param_list.push(param)
select_name += '_'
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
}
console.log(param_list,"param_list")
from_date=new Date().getTime()-300000 //5 minute data
hostname=param_list[0]
TypeOfParameter= param_list[1]
sub_type_parameter=param_list[param_list.length-1]
data = {'type':TypeOfParameter,'hostname':hostname,'param':sub_type_parameter,'from-date':from_date}
var sub_type;
if(param_list.length==4){
sub_type=param_list[2]
data['sub-type'] = sub_type
}
else
{
sub_type=sub_type_parameter
}
// console.log(hostname,TypeOfParameter,sub_type,sub_type_parameter)
data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
requestData(data)
$('#loadingmessage').show(); // show the loading message.
chart = $('#first').highcharts();
if(TypeOfParameter=='cpu')
{
console.log("adding axis")
chart.addAxis({ // Primary yAxis
id:'Cpu_axis'+sub_type_parameter,
labels: {
formatter: function() {
return this.value;
},
style: {
color: '#89A54E'
}
},
title: {
text: "core "+ sub_type+ " "+sub_type_parameter,
style: {
color: '#89A54E'
}
},
lineWidth: 1,
lineColor: '#08F'
});
console.log("adding series")
chart.addSeries({
id:sub_type+sub_type_parameter,
name: "core "+sub_type+" "+sub_type_parameter,
data :[],
tooltip : {
valueSuffix: ' %'
},
yAxis:'Cpu_axis'+sub_type_parameter
})
console.log("series out")
}
if(TypeOfParameter=='memory')
{
chart.addAxis ({
id:'memory'+sub_type_parameter,
labels:{
formatter: function() {
return this.value +'%';
},
style: {
color: '#89C54F'
}
},
title: {
text:sub_type+" "+sub_type_parameter
},
lineWidth: .5,
lineColor: '#08F',
opposite: true
});
chart.addSeries({
id:sub_type+sub_type_parameter,
name: sub_type+'memory usage',
data: [],
tooltip: {
valueSuffix: '%'
},
yAxis:'memory'+sub_type_parameter
});
}
if(TypeOfParameter=='disk')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'disk Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'disk',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'disk',
data: []
}]
});
}
if(TypeOfParameter=='db')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'mongo Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'mmongo',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'mongo',
data: []
}]
});
}
if(TypeOfParameter=='redis')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'redis Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'redis',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'redis',
data: []
}]
});
}
$('#loadingmessage').hide(); // hide the loading message
}
)
});
i am stuck on this problem for quite a while. and still not able to figure out the solution.
here is the full code link
someone please please help. feeling frustrated ..:-(
As you know the addPoint method is bit dangerous when dealing with quite lots points. It is recommended to disable redraw per point when dealing with many new points - more info http://api.highcharts.com/highcharts#Series.addPoint() , I notice you are doing that already in the loop statement, but why did you commented out? have you tried enabling again. Make sure chart.redraw works by adding a new redraw chart event, and set an alert or console log.
Also you may try using, below as part of ajax, instead of cache:false. I had some problems in past.
headers: { 'Cache-Control': 'no-cache' }
Cheers

Loading JQuery dynamically but highcharts fails

I am not really a javascript programmer but I have been struggling for a long time with this problem - any help would be very much appreciated.
In the following jsfiddle - if Jquery is selected from the frameworks and extensions tab the highcharts chart works fine. But the point of the code is I need to dynamically load a different jquery version - to use the chart as a widget of sorts. But changing it to no library (pure JS) the chart does not load.
http://jsfiddle.net/hgera000/JcVLQ/3/
A large part of my code I'm getting from here:
http://alexmarandon.com/articles/web_widget_jquery/
Thanks very much
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.7.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
var chart;
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
chart = new Highcharts.Chart({
credits: {
enabled: true,
text: '',
href: ''
},
chart: {
renderTo: 'bm-container',
events: {
click: function () {
window.open('http://www.betmetrix.com', '_blank')
},
},
backgroundColor: '#FFFFFF',
zoomType: 'xy',
type: 'line',
marginLeft: 40,
marginRight: 40,
marginBottom: 40,
},
title: {
text: 'Election Worm',
x: -5,
style: {
color: '#000000',
fontWeight: 'bold',
fontSize: '17pt'
}
},
subtitle: {
text: 'Estimated Probability of Victory',
x: -5,
style: {
color: '#000000',
//fontWeight: 'bold',
fontSize: '13pt'
}
},
xAxis: {
type: 'datetime',
minRange: 7 * 24 * 3600000, // 1 week
dateTimeLabelFormats: {
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e %b',
week: '%e %b',
month: '%b \'%y',
year: '%Y'
},
//max: lnp[lnp.length-1][0]+604800000,
//tickInterval: 24*3600*1000*120,
//showFirstLabel: false,
minTickInterval: 1 * 24 * 3600000, //1 day
//maxTickInterval: 1 * 24 * 3600000*365, //30 day
startOnTick: false,
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
}
},
yAxis: [{
//LHS axis
title: {
text: '%',
align: 'high',
rotation: 0,
offset: 10,
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
showLastLabel: false,
showFirstLabel: false,
minRange: 3,
minTickInterval: 1,
min: 0,
max: 100,
opposite: false,
startOnTick: true,
//tickInterval: 5,
allowDecimals: false
}, {
//RHS axis
title: {
text: '%',
align: 'high',
rotation: 0,
offset: 20,
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
linkedTo: 0,
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
showLastLabel: false,
minTickInterval: 1,
minRange: 3,
showFirstLabel: false,
startOnTick: true,
min: 0,
max: 100,
opposite: true,
//tickInterval: 10,
allowDecimals: false
}],
tooltip: {
xDateFormat: '%d-%b-%Y %l%P', //'%d-%b-%Y %l%P'
valueSuffix: '%',
valueDecimals: 1
//formatter: function () {
// return this.x + '<br/><b>' + this.series.name + ':' + '</b>' + this.y + '%';
//}
},
legend: {
enabled: false
// layout: 'vertical',
// align: 'right',
// verticalAlign: 'left',
// x: -20,
// y: 10,
// borderWidth: 0
},
series: [{
name: 'Coalition',
data: lnp,
marker: {
enabled: false
},
yaxis: 0
}, {
name: 'ALP',
data: alp,
marker: {
enabled: false
},
yaxis: 0
}],
exporting: {
enabled: false
}
});
});
}
})(); // We call our anonymous function immediately
Although the alexmarandon.com web widget tutorial mentions other libraries, maybe your case would be better suited with an all dynamic "chain load" approach. Once the jquery dynamic load is complete, don't go directly to main(), but instead move on and chain load Highcharts dynamically as well. Add this one more function, remove static, external reference to Highcharts.js, and then replace the call back to scriptLoadHandler() with a call to this chainLoadHighchharts() function, which itself will then pass on to the original scriptLoadHandler().
function chainLoadHighCharts() {
var Highcharts;
/******** Ok, /now/ dynamically load up highchart too... *********/
if (window.Highcharts === undefined) {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://code.highcharts.com/highcharts.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler(); //here is the call that was orginally called directly from the jquery dynamic load.
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
scriptLoadHandler();
// script_tag.setAttribute("src","http://code.highcharts.com/modules/exporting.js");
}
}
Still needs a bit of tightening, but it ran without error for me on jsfiddle.
http://jsfiddle.net/JcVLQ/5/

Categories

Resources