How to migrate a chart from Highcharts Demo to Highcharts Cloud - javascript

Perhaps others have seen the amazing Force-Directed Network Graph demo which I would dearly love to adapt to my own ends. However, simply copying the code over doesn't seem to be enough.
I'm no longer using the inline-defined data but rather data coming from a Google Sheets file. And I've morphed the code so that it contains more columns in the data. Here's a jsfiddle though without the Google Sheets connection.
(I have tried the Google Sheets connection there but it doesn't work -- for reasons yet to be discovered. The connection is public if anyone wants to fiddle.)
So here's the code that I've dumped into the "Custom Code" panel in the "Customize" section of Highcharts Cloud.
Highcharts.addEvent(
Highcharts.seriesTypes.networkgraph, 'afterSetOptions',
function (e) {
var colors = Highcharts.getOptions().colors,
i = 0,
nodes = {};
e.options.data.forEach(function (link) {
if (link[0] === 'Keyword Research') {
nodes['Keyword Research'] = {
id: 'Keyword Research',
marker: { radius: link[2] }
};
nodes[link[1]] = {
id: link[1], marker: { radius: link[2] }, color: colors[i++]
};
}
else if
(nodes[link[0]] && nodes[link[0]].color) {
nodes[link[1]] = {
id: link[1], color: nodes[link[0]].color
};
}
});
e.options.nodes = Object.keys(nodes).map(function (id) { return nodes[id]; });
}
);
Highcharts.chart('highcharts-container',
{
chart: { type: 'networkgraph', height: '100%' },
title: { text: 'The Indo-European Language Tree' },
subtitle: { text: 'A Force-Directed Network Graph in Highcharts' },
plotOptions: { networkgraph: { keys: ['from', 'to'], layoutAlgorithm: { enableSimulation: true, friction: -0.9 } } },
series: [{
dataLabels: { enabled: true, linkFormat: '' },
"data": {
"googleSpreadsheetKey": "1kQKkN4auaxsgwms057FkJ7l5g3mhBjR5vp5PPpStDBQ",
"dataRefreshRate": false,
"enablePolling": true,
"startRow": "2",
"endRow": "14",
"startColumn": "1",
"endColumn": "3"
}
}]
}
);
It'd be great to find out how to make it work.
LATER
Setup for GoogleDrive included as a comment in the jsfiddle.

I have not solved this 100%, but have fixed one issue which may lead you to get an answer. You have your data element inside series, but when looking at the highcharts api for googleSpreadsheetKey, they have put it outside series. So, try the following. When I do, I get CORS error in the console.
Highcharts.addEvent(
Highcharts.seriesTypes.networkgraph, 'afterSetOptions',
function (e) {
var colors = Highcharts.getOptions().colors,
i = 0,
nodes = {};
e.options.data.forEach(function (link) {
if (link[0] === 'Keyword Research') {
nodes['Keyword Research'] = {
id: 'Keyword Research',
marker: { radius: link[2] }
};
nodes[link[1]] = {
id: link[1], marker: { radius: link[2] }, color: colors[i++]
};
}
else if
(nodes[link[0]] && nodes[link[0]].color) {
nodes[link[1]] = {
id: link[1], color: nodes[link[0]].color
};
}
});
e.options.nodes = Object.keys(nodes).map(function (id) { return nodes[id]; });
}
);
Highcharts.chart('highcharts-container',
{
chart: { type: 'networkgraph', height: '100%' },
title: { text: 'The Indo-European Language Tree' },
subtitle: { text: 'A Force-Directed Network Graph in Highcharts' },
plotOptions: { networkgraph: { keys: ['from', 'to'], layoutAlgorithm: { enableSimulation: true, friction: -0.9 } } },
series: [{
dataLabels: { enabled: true, linkFormat: '' }
}],
"data": {
"googleSpreadsheetKey": "1kQKkN4auaxsgwms057FkJ7l5g3mhBjR5vp5PPpStDBQ",
"dataRefreshRate": false,
"enablePolling": true,
"startRow": "2",
"endRow": "14",
"startColumn": "1",
"endColumn": "3"
}
});

Highcharts Cloud doesn't support force directed graph for now.
This series requires network graph module (https://code.highcharts.com/modules/networkgraph.js) which is not imported for charts created in Cloud. Here's the list of imported scripts:
var scripts = [
"highcharts.js",
"modules/stock.js",
"highcharts-more.js",
"highcharts-3d.js",
"modules/data.js",
"modules/exporting.js",
"modules/funnel.js",
"modules/solid-gauge.js",
"modules/export-data.js",
"modules/accessibility.js",
"modules/annotations.js"
];

Related

Apexcharts cursor pointer

I used apexcharts.js for making chartbar on js. So i want to change cursor to pointer. help please! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
my-code!
var options = {
series: [{
name: 'series1',
data: [60, 85, 75, 120, 100, 109, 97]
}],
toolbar: {
show: false,
},
chart: {
height: 350,
type: 'area',
fontFamily: 'Proxima Nova',
toolbar: {
show: false
},
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth'
},
xaxis: {
categories: ["Янв", "Фев", "Март", "Апр", "Май", "Июнь", "Июль", "Авг", "Сен", "Окт", "Ноя", "Дек"]
},
tooltip: {
x: {
format: 'dd/MM/yy HH:mm'
},
},
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
I had encountered the same problem. I will present you two solutions:
1st method : Found on Github
You can set the cursor to point with:
chart: {
...
events: {
dataPointMouseEnter: function(event) {
event.path[0].style.cursor = "pointer";
}
}
}
See more details in this github link : https://github.com/apexcharts/apexcharts.js/issues/1466
2nd method : My own method
You can target the class name of the apexchart component via Inspector, then at the code level add the following property to this class :
cursor: pointer
Example :
// Change cursor on hover
.apexcharts-pie {
cursor: pointer;
}
I had same problem. Here is two solutions:
chart: {
width: 320,
type: ...,
events: {
dataPointMouseEnter: function(event) {
event.target.style.cursor = "pointer";
// or
event.fromElement.style.cursor = "pointer";
}
},
}

Hide a category when a series name has no value attributed to it highchart

I have simplified my graph below for demo purposes but i have a lot of categories but not all series names will have a value of those categories. So when i select that series name how would i go about making 0 value categories disappear.
For example below when selecting person 1 the service 1 category should disappear instead of remain with no bars for it
Highcharts.chart('container', {
chart : {type: 'column'},
xAxis: {
categories: ["service1", "service2", "service3", "service"] ,
showEmpty : true ,
ordinal: false
},
series: [{
name: 'person1',
data: [0,2,3],
},
{ name : 'person2',
data: [10,6,5]
}]
});
link to the code https://jsfiddle.net/uroepk1j/
ppotaczek's Code from JSFiddle
Highcharts.chart('container', {
chart: {
type: 'column',
ignoreHiddenSeries: true
},
plotOptions: {
column: {
pointPlacement: null,
events: {
legendItemClick: function() {
var points = this.data,
hideCategory = false,
breaks = [],
stop,
series = this.chart.series;
this.chart.xAxis[0].update({
breaks: []
});
this.visible = !this.visible;
points.forEach(function(p, i) {
stop = false;
series.forEach(function(s) {
if (!stop && (!s.visible || s.data[i].y === 0)) {
hideCategory = true;
} else {
stop = true;
hideCategory = false;
}
}, this);
if (hideCategory) {
breaks.push({
from: i - 0.5,
to: i + 0.5,
breakSize: 0
})
}
hideCategory = false;
}, this);
this.visible = !this.visible;
this.chart.xAxis[0].update({
breaks: breaks
});
}
}
},
},
xAxis: {
categories: ['Col 1', 'Col 2', 'Col 3']
},
series: [{
name: 'person1',
data: [2, 0, 3],
},
{
name: 'person2',
data: [10, 1, 5]
}
]
});
Thanks for your help
You can use broken-axis module and insert breaks in place of the category in which there are no points, for example:
plotOptions: {
column: {
grouping: false,
pointPlacement: null,
events: {
legendItemClick: function() {
if (!this.visible) {
breaks[this.index] = {}
this.chart.xAxis[0].update({
breaks: breaks
});
} else {
breaks[this.index] = {
from: this.xData[0] - 0.5,
to: this.xData[0] + 0.5,
breakSize: 0
}
this.chart.xAxis[0].update({
breaks: breaks
});
}
}
}
},
}
Live demo: http://jsfiddle.net/BlackLabel/4utq7e3n/
API Reference: https://api.highcharts.com/highcharts/xAxis.breaks

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 :)

Highcharts bar chart wont animate

Not sure why because I have done it in the past, but I have a Highcharts bar chart and it won't animate. This is the declaration of the chart,
function initializeData() {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
var newdata = [];
for (x = 0; x < 5; x++) {
newdata.push({
name: setName($scope.jsondata[x].name),
y: $scope.jsondata[x].data[0],
color: getColor($scope.jsondata[x].data[0])
});
}
$scope.chart.series[0].setData(newdata);
});
mainInterval = $interval(updateData, 5000);
}
function updateData() {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
console.debug("here");
for (x = 0; x < 5; x++) {
$scope.chart.series[0].data[x].update({
y: $scope.jsondata[x].data[0],
color: getColor($scope.jsondata[x].data[0])
});
}
});
}
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar',
animation: true,
events: {
load: initializeData
}
},
title: {
text: ''
},
xAxis: {
type: 'category',
labels: {
style: {
fontSize: '11px'
}
}
},
yAxis: {
min: 0,
max: 100,
title: {
text: 'Total Score',
align: 'high'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: 'Total Score <b>{point.y:.3f}</b>'
},
series: [{
name: 'Active Users',
data: [],
dataLabels: {
enabled: true,
rotation: 30,
style: {
fontSize: '10px',
fontFamily: 'Verdana, sans-serif'
},
format: '{point.y:.3f}', // one decimal
}
}]
});
And as you can see I have animate : true, so I am not sure what is the problem here. I have this older plunker where all of the data is in separate series, but it animates fine. But this is the plunker I am working on and having trouble with. They are like identical basically. In the newer one I broke out the initialization of data into its own method, but that is the only real main difference.
Some edits:
So as I was saying, I have done things this way with an areaspline chart (I know it was said they work a bit different but they are set up identically).
function initializeData() {
$interval.cancel(mainInterval);
$scope.previousPackets = '';
$http.get("https://api.myjson.com/bins/nodx").success(function(returnedData) {
var newdata = [];
var x = (new Date()).getTime();
for (var step = 9; step >= 0; step--) {
newdata.push([x - 1000 * step, 0]);
}
$scope.chart.series[0].setData(newdata);
});
mainInterval = $interval(updateData, 2000);
}
function updateData() {
$http.get(url + acronym + '/latest').success(function(returnedData) {
var x = (new Date()).getTime();
if ($scope.previousPackets != returnedData[0].numPackets) {
$scope.chart.series[0].addPoint([x, returnedData[0].numPackets], true, true);
$scope.previousPackets = returnedData[0].numPackets;
} else {
$scope.chart.series[0].addPoint([x, 0], true, true);
}
});
}
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: initializeData
}
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Packets'
},
plotLines: [{
value: 0,
width: 1,
color: '#d9534f'
}]
},
tooltip: {
formatter: function() {
return Highcharts.numberFormat(this.y) + ' packets<b> | </b>' + Highcharts.dateFormat('%H:%M:%S', this.x);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Packets',
data: []
}]
});
I also updated the first chunk of code with the initializeData() method and updateData() method which are seemingly identical in both different charts.
It looks like it plays an important role if you provide your data at chart initialization or after. For simplicity I refactored your code a little
function initializeChart(initialData, onload) {
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar',
animation: true,
events: {
load: onload
}
....
series: [{
name: 'Active Users',
data: initialData,
dataLabels: {
enabled: true,
format: '{point.y:.3f}', // one decimal
}
}]
});
}
function getData(callback) {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
var newdata = [];
for (x = 0; x < 5; x++) {
newdata.push([setName(ret[x].name), ret[x].data]);
}
callback(newdata);
});
}
As a result your two planks are in essense reduced to two methods below. The first initializes chart with preloaded data and the second updates data in existing chart.
function readDataFirst() {
getData(function(newdata) {
initializeChart(newdata);
});
}
function initializeChartFirst() {
initializeChart([], function() {
getData(function(newdata) {
$scope.chart.series[0].setData(newdata);
})
});
}
The first one animates fine while the second does not. It looks like highcharts skips animation if dataset is not initial and is treated incompatible.
However if you really want to have animation in your current plant (chart first workflow) you can achieve that by initializing first serie with zeros and then with the real data. This case it will be treated as update
function forceAnimationByDoubleInitialization() {
getData(function(newdata) {
initializeChart([]);
var zerodata = newdata.map(function(item) {
return [item[0], 0]
});
$scope.chart.series[0].setData(zerodata);
$scope.chart.series[0].setData(newdata);
});
All these options are available at http://plnkr.co/edit/pZhBJoV7PmjDNRNOj2Uc

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

Categories

Resources