I am trying to draw a dynamic, mixed bar and line graph using Highchart.js. I am getting live data to my webpage using socket.io (I'm using Flask as my webserver so using Flask-socketIO).
I am able to print the data coming to my webpage using console.log, but I am missing something for which it is not rendered in the chart.
I am trying to add xAxis as well as both the Series value.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<link href="../static/css/authz.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myChart = Highcharts.chart('containerX', {
chart: {
zoomType: 'xy',
events: {
load: function () {
// set up the updating of the chart on each sample
var categories = this.xAxis[0].categories;
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
var series1 = this.series[0]
var series2 = this.series[1]
socket.on('my_response_data', function (sample) {
//add chart data to series
var x = sample.logTime
var y = sample.logDuration
var z = sample.totalSession
console.log( x + " " + y + " " + z) //Printing properly to console e.g 2018-01-25T03:58:35.781 3 211
categories.push(sample.logTime)
series1.addPoint(y, false, true);
series2.addPoint(z, false, true);
myChart.redraw();
});
}
},
},
title: {
text: 'Sacred Tests'
},
subtitle: {
text: 'Source: My Secret Source'
},
xAxis: [{
categories: [],
crosshair: true
}],
yAxis: [{ // Primary yAxis
title: {
text: 'Sessions',
style: {
color: Highcharts.getOptions().colors[1]
}
},
labels: {
format: '{value}',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'Duration',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} ms',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Sessions',
type: 'column',
yAxis: 1,
data: [],
tooltip: {
valueSuffix: ''
}
}, {
name: 'Duration',
type: 'spline',
data: [],
tooltip: {
valueSuffix: 'ms'
}
}]
});
});
</script>
</head>
<body>
<div id="containerX" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
It's a problem with displaying only one point at a time with addPoint(point, redraw, shift, animation) and setting shift=true. That will remove previous point and chart will look empty.
Simple solution is to use:
series1.addPoint(y, false, false, false);
series2.addPoint(z, false, false, false);
myChart.redraw();
I have a code for a bar chart and it is working well but this code has static values but I want to take the values from a server and every time have a different chart (I mean I dont want to give any values in the code).How can I make that?
This is the code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.0.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
<script>
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Top 10 HashTags'
},
xAxis: {
categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania'],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Number of repeated hashTags ',
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: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series: [ {
name: 'Year 2012',
data: [1052, 954, 4250, 740, 38]
}]
});
});
</script>
A little example to you. The first column is the xAxis and the others, series. I hope this help you.:
<?php
$sql5 = mysqli_query($bd,'SELECT tx_rend_escolas.ano, tx_rend_escolas.ap_med, tx_rend_escolas.rep_med, tx_rend_escolas.abd_med FROM tx_rend_escolas WHERE tx_rend_escolas.fk_cod_entidade = 21438200 ORDER BY tx_rend_escolas.ano ASC;') or die(mysqli_error());
$linhas5 = mysqli_num_rows($sql5);
$proc4 = array();
$proc5 = array();
$proc6 = array();
$proc7 = array();
while ($docs = mysqli_fetch_assoc($sql5)) {
$proc4[] = "'".$docs['ano']."'";
$proc5[] = $docs['ap_med'];
$proc6[] = $docs['rep_med'];
$proc7[] = $docs['abd_med'];
}
$proc4 = implode(",", $proc4);
$proc5 = implode(",", $proc5);
$proc6 = implode(",", $proc6);
$proc7 = implode(",", $proc7);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'area'
},
title: {
text: 'Historic and Estimated Worldwide Population Distribution by Region'
},
subtitle: {
text: 'Source: Wikipedia.org'
},
xAxis: {
categories: [<?php echo $proc4;?>],
tickmarkPlacement: 'on',
title: {
enabled: false
}
},
yAxis: {
title: {
text: 'Percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.percentage:.1f}%</b><br/>',
shared: true
},
plotOptions: {
area: {
stacking: 'percent',
lineColor: '#ffffff',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#ffffff'
}
}
},
series: [{
name: 'Aprovação',
data: [<?php echo $proc5;?>]
}, {
name: 'Reprovação',
data: [<?php echo $proc6;?>]
}, {
name: 'Abandono',
data: [<?php echo $proc7;?>]
}]
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Highcharts - Multiple pie charts from json
Let's say I have a server with 4 hard drives. How do I show 4 pie charts, one for each hard drive? It works if the chart type is stacked column (code below).
JSON produces this output:
[{
"name":"Drive",
"data":["C:","D:","E:","F:"]},{
"name":"Free",
"data":[673869,2267920,105627,307096]},{
"name":"Used",
"data":[94029,2264810,6373,104]
}]
And my script code (for stacked column):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stacked column chart with data from MySQL using Highcharts</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
colors: ['#50B432', '#ED561B'],
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Server',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Used / Free'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +' '+ Highcharts.numberFormat(this.percentage, 2) +' %';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: '#000000',
formatter: function() {
return bytes(this.point.y, true);
}
}
}
},
series: []
}
$.getJSON("data2.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
});
function bytes(bytes, label) {
if (bytes == 0) return '';
var s = ['MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
var value = ((bytes/Math.pow(1024, Math.floor(e))).toFixed(2));
e = (e<0) ? (-e) : e;
if (label) value += ' ' + s[e];
return value;
}
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Thank you for any suggestions.
You can iterate on each json item and create new div (by for example append) and init chart.
What is important, all values in data should be numbers, not strings like you have.
Example:
http://jsfiddle.net/9ov3en2t/
$(function () {
var json = [{
"name": "Drive",
"data": ["C:", "D:", "E:", "F:"]
}, {
"name": "Free",
"data": [673869, 2267920, 105627, 307096]
}, {
"name": "Used",
"data": [94029, 2264810, 6373, 104]
}];
var each = Highcharts.each,
$charts = $('#charts');
each(json,function(item, i) {
$charts.append('<div id="container' + i + '"></div>');
var $chart = $('#container' + i);
$chart.highcharts({
chart:{
type:'pie'
},
series:[{
name: item.name,
data: item.data
}]
});
});
});
I am trying to build a highchart on my page. I do get the chart frame and title but now lines or legends. When I do:
document.write(output)
[ {"name":"dc1_sx02","data":[[1406269800,0.092],[1406271600,0.092],[1406273400,0.091],[1406275200,0.093],[1406277000,0.091],[1406278800,0.09],[1406280600,0.093],[1406282400,0.094],[1406284200,0.092],[1406286000,0.09],[1406287800,0.094]]},{"name":"dc1_sx03","data":[[1406340000,0.01],[1406341800,0.009],[1406343600,0.009],[1406345400,0.009],[1406347200,0.009],[1406349000,0.009],[1406350800,0.009],[1406352600,0.009],[1406356200,0.01],[1406358000,0.009],[1406359800,0.009],[1406361600,0.009],[1406365200,0.009],[1406367000,0.009],[1406368800,0.009],[1406370600,0.009],[1406374200,0.009],[1406376000,0.009],[1406377800,0.01],[1406379600,0.009],[1406383200,0.009],[1406385000,0.009],[1406386800,0.009],[1406388600,0.009],[1406392200,0.009],[1406394000,0.009],[1406475000,0.009],[1406476800,0.009],[1406478600,0.009],[1406480400,0.009],[1406482200,0.009],[1406484000,0.009],[1406485800,0.009],[1406487600,0.009],[1406489400,0.009],[1406491200,0.011],[1406493000,0.01],[1406494800,0.009],[1406496600,0.009],[1406498400,0.009],[1406500200,0.01],[1406502000,0.009],[1406503800,0.009],[1406505600,0.009],[1406507400,0.009],[1406509200,0.009],[1406511000,0.009],[1406512800,0.009],[1406514600,0.009],[1406516400,0.009],[1406518200,0.009],[1406520000,0.009],[1406521800,0.009],[1406523600,0.009],[1406525400,0.009],[1406527200,0.009],[1406529000,0.01],[1406530800,0.009],[1406532600,0.009],[1406534400,0.009],[1406536200,0.009],[1406538000,0.009],[1406539800,0.009],[1406541600,0.009],[1406543400,0.009],[1406547000,0.009],[1406548800,0.009],[1406550600,0.009],[1406552400,0.009],[1406554200,0.009],[1406556000,0.009],[1406557800,0.009],[1406559600,0.009],[1406561400,0.009],[1406563200,0.009],[1406565000,0.009],[1406566800,0.009],[1406568600,0.009],[1406570400,0.009],[1406572200,0.009],[1406574000,0.009],[1406575800,0.009],[1406577600,0.009],[1406579400,0.009],[1406581200,0.009],[1406583000,0.009],[1406584800,0.009],[1406586600,0.009],[1406588400,0.009],[1406590200,0.009],[1406592000,0.009],[1406593800,0.009],[1406595600,0.009],[1406597400,0.009],[1406599200,0.009],[1406601000,0.009],[1406602800,0.009],[1406604600,0.01],[1406606400,0.009],[1406608200,0.009],[1406610000,0.009],[1406611800,0.009],[1406613600,0.009],[1406615400,0.01],[1406617200,0.011],[1406619000,0.012],[1406620800,0.012],[1406622600,0.012],[1406624400,0.012],[1406626200,0.012],[1406628000,0.012],[1406629800,0.012],[1406631600,0.012],[1406633400,0.012],[1406635200,0.012],[1406637000,0.011],[1406638800,0.012],[1406640600,0.012],[1406642400,0.012],[1406644200,0.012],[1406646000,0.012],[1406647800,0.013],[1406649600,0.012],[1406651400,0.012],[1406653200,0.012],[1406655000,0.012]]} ]
I do get the nicely formated json output. Any ideas what I might be missing from this script:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<!-- Include order: first jquery, then opencpu.js, and then your code -->
<script src="opencpu/jquery-1.10.2.min.js"></script>
<script src="opencpu/opencpu-0.4.js"></script>
<script src="opencpu/highcharts.js"></script>
<script src="opencpu/export-csv.js"></script>
<script>
//init this script when the page has loaded
$(document).ready(function(){
$("#submitbutton").on("click", function(){
//disable the button to prevent multiple clicks
$("#submitbutton").attr("disabled", "disabled");
var myname = $("#namefield").val();
//perform the request
var req = ocpu.rpc("output", {
myname : myname
}, function(output){
document.write(output);
//alert(output);
$('#output').highcharts({
//$("#output").highcharts('StockChart',{
chart: {
borderColor: '#98AFC7',
borderRadius: 20,
borderWidth: 1,
renderTo: 'output',
type: 'line',
marginRight: 10,
zoomType: 'x',
resetZoomButton: {
position: {
x: -50,
y: -50
}
}
},
plotOptions: {
line: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 5
}
}
},
exporting: {
enabled: true
},
legend: {
enabled: true,
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderWidth: 2,
shadow: true
},
rangeSelector: {
enabled:true
},
scrollbar: {
enabled: true
},
navigator : {
enabled : true
},
xAxis: {
type:'datetime',
gridLineColor: '#EEEEEE',
gridLineWidth: 1
},
yAxis: { // Primary yAxis
labels: {
style: {
color: 'blue'
}
},
gridLineColor: '#EEEEEE',
gridLineWidth: 1,
title: {
text: '% CPU Utilization',
fontSize: '50px',
style: {
color: 'blue'
}
}
},
credits: {
enabled: false
},
title: {
text: '% CPU UTILIZATION',
style: {
color: '#333000',
fontSize: '14px'
}
},
tooltip: {
positioner: function(){
return{x:20,y:-5};
},
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}<b>',
valueDecimals: 2
},
series:output
});
});
//if R returns an error, alert the error message
req.fail(function(){
alert("Server error: " + req.responseText);
});
//after request complete, re-enable the button
req.always(function(){
$("#submitbutton").removeAttr("disabled")
});
});
});
</script>
<style>
#output{
height: 600px;
width: 1500px;
border: 0px;
padding: 3px;
}
</style>
</head>
<body>
<h1>My First HighStock Chart!!!!</h1>
<b>Your name: </b> <input type="text" id="namefield">
<button id="submitbutton" type="button">Submit to server!</button>
<div id="output"> </div>
<br />
</body>
</html>
I did a
document.write(output)
and copyied the output to the jsfiddle at this address:
http://jsfiddle.net/gsaray101/rmL1573f/
it works there so I am assuming the data is accurate, any ideas what might be happening?
I resolved this problem by using JSON.parse() function in the ui as follows:
var data=output;
data=JSON.parse(data);
after hours of troubleshooting about why my chart is not loading, i found using jquery.ba-resize and jquery.flot.resize concurrently with highstock in one page cause this error:
uncaught typeerror: cannot read property 'width' of undefined
currently im tring to integrate one of highstock examples into my page, which could be found at highstock demos.
any idea on how to fix this?
thanks
edit2: jsfiddle: http://jsfiddle.net/CFPqG/
actual code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'],
colors = Highcharts.getOptions().colors;
$.each(names, function(i, name) {
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename='+ name.toLowerCase() +'-c.json&callback=?', function(data) {
seriesOptions[i] = {
name: name,
data: data
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if (seriesCounter == names.length) {
createChart();
}
});
});
// create the chart when all data is loaded
function createChart() {
$('#container').highcharts('StockChart', {
lang: {
rangeSelectorZoom: ''
},
chart: {
type: 'area'
},
legend: {
enabled: true,
borderRadius: 0,
layout: 'horizontal',
backgroundColor: null,
align: 'right',
verticalAlign: 'top',
floating: true,
borderWidth: 0,
y: 20
},
colors: [
'#71c49a',
'#444444',
'#777777',
'#910000',
'#1aadce',
'#492970',
'#f28f43',
'#77a1e5',
'#c42525',
'#a6c96a'
],
exporting: {
enabled: false
},
credits: {
enabled: false
},
xAxis: {
lineColor: '#d8efe3',
labels: {
style: {
color: '#71c49a'
},
}
},
yAxis: {
lineColor: '#d8efe3',
gridLineColor: '#d8efe3',
labels: {
style: {
color: '#71c49a'
},
formatter: function() {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: '#71c49a'
}]
},
scrollbar: {
enabled: false
},
rangeSelector: {
selected: 1,
inputEnabled: false,
buttonSpacing: 5,
labelStyle: {
color: '#71c49a',
fontWeight: 'bold'
},
},
navigator: {
handles: {
backgroundColor: '#d8efe3',
borderColor: '#71c49a'
},
series: {
color: '#71c49a'
}
},
plotOptions: {
area: {
lineWidth: 3,
shadow: true,
marker: {
enabled: true,
fillColor: '#FFFFFF',
lineWidth: 2,
lineColor: null,
symbol: 'circle',
radius: 3,
states: {
hover: {
enabled: true
}
}
}
},
series: {
compare: 'percent',
fillOpacity: 0.7
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
</script>
</head>
<body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 600px"></div>
<script src="your-path/jquery.ba-resize.js"></script>
<script src="your-path/jquery.flot.resize.js" type="text/javascript"></script>
</body>
</html>
Looks like that 'resize' library overwrites some jQuery function, which doesn't work the same way anymore.. ? In that case I advice to use Highcharts standalone version, see: http://jsfiddle.net/CFPqG/1/
<script type="text/javascript" src="https://rawgithub.com/cowboy/jquery-resize/v1.1/jquery.ba-resize.js"></script>