Live multiple series with highchart - javascript

I am trying to display 10 series simultaneously on highcharts. With the following code.
function requestData() {
$.ajax({
url: 'Default3.aspx',
dataType: 'json',
error: function (point) {
var series = chart.series[10],
shift = series.data.length > 50; // shift if the series is longer than 20
chart.series[0].addPoint([0, 1], true, true);
chart.series[1].addPoint([0, 2], true, true);
chart.series[2].addPoint([0, 3], true, true);
chart.series[3].addPoint([0, 4], true, true);
chart.series[4].addPoint([0, 5], true, true);
chart.series[5].addPoint([0, 6], true, true);
chart.series[6].addPoint([0, 7], true, true);
chart.series[7].addPoint([0, 8], true, true);
chart.series[8].addPoint([0, 9], true, true);
chart.series[9].addPoint([0, 10], true, true);
// call it again after one second
setTimeout(requestData, 5000);
},
success: function (point) {
var series = chart.series[10],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
chart.series[0].addPoint([0, 1], true, true);
chart.series[1].addPoint([0, 2], true, true);
chart.series[2].addPoint([0, 3], true, true);
chart.series[3].addPoint([0, 4], true, true);
chart.series[4].addPoint([0, 5], true, true);
chart.series[5].addPoint([0, 6], true, true);
chart.series[6].addPoint([0, 7], true, true);
chart.series[7].addPoint([0, 8], true, true);
chart.series[8].addPoint([0, 9], true, true);
chart.series[9].addPoint([0, 10], true, true);
// call it again after one second
setTimeout(requestData, 5000);
},
cache: false
});
}
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
events: {
load: requestData
}
},
title: {
text: 'Sensor Data Vs. Time'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
data: []
},{
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}]
});
});
Legends of the series is coming on the chart but it is not displaying the data.

I advice replace this:
chart.series[0].addPoint([0, 1], true, true);
//other points as first
chart.series[9].addPoint([0, 10], true, true);
with
chart.series[0].addPoint([0, 1], false, true);
//other points as first
chart.series[9].addPoint([0, 10], true, true);
Points cannot be added to the empty chart, dynamically, but you can set null value on data like here http://jsfiddle.net/g2tka/1/ or use addSeries.

I did some modification on trial and error basis and got it working, Actually i have to use eval function which I was not using previously.
Here is the answer
JavaScript
function requestData() {
$.ajax({
url: 'Default3.aspx',
dataType: 'json',
error: function (point) {
var series = chart.series[0],
shift = series.data.length > 50; // shift if the series is longer than 20
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
chart.series[2].addPoint([values[0], values[3]], true, shift);
chart.series[3].addPoint([values[0], values[4]], true, shift);
chart.series[4].addPoint([values[0], values[5]], true, shift);
chart.series[5].addPoint([values[0], values[6]], true, shift);
chart.series[6].addPoint([values[0], values[7]], true, shift);
chart.series[7].addPoint([values[0], values[8]], true, shift);
chart.series[8].addPoint([values[0], values[9]], true, shift);
chart.series[9].addPoint([values[0], values[10]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 5000);
},
success: function (point) {
var series = chart.series[0],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
chart.series[2].addPoint([values[0], values[3]], true, shift);
chart.series[3].addPoint([values[0], values[4]], true, shift);
chart.series[4].addPoint([values[0], values[5]], true, shift);
chart.series[5].addPoint([values[0], values[6]], true, shift);
chart.series[6].addPoint([values[0], values[7]], true, shift);
chart.series[7].addPoint([values[0], values[8]], true, shift);
chart.series[8].addPoint([values[0], values[9]], true, shift);
chart.series[9].addPoint([values[0], values[10]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 5000);
},
cache: false
});
}
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Sensor Data Vs. Time'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Pressure 1 (PSI)',
data: []
}, {
name: 'Flow 1 (GPM)',
data: []
}, {
name:'Temperature 1 (C)',
data: []
}, {
name: 'Speed 1 (RPM)',
data: []
}, {
name: 'Power 1 (kW)',
data: []
}, {
name:'Pressure 2 (PSI)',
data: []
}, {
name:'Flow 2 (GPM)',
data: []
}, {
name:'Temperature 2 (C)',
data: []
}, {
name: 'Speed 2 (RPM)',
data: []
}, {
name: 'Power 2 (kW)',
data: []
}]
});
});
Server Side Code (C#)
public partial class Default3 : System.Web.UI.Page
{
public DataTable dt = new DataTable();
public string DATA;
List<string> hidXCategories11 = new List<string>();
public string chartData
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
GetData();
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var timeDiff = DateTime.Now - new DateTime(1970, 1, 1);
var totaltime = timeDiff.TotalMilliseconds;
List<double> _data = new List<double>();
foreach (DataRow row in dt.Rows)
{
_data.Add(totaltime);
_data.Add((double)Convert.ToDouble(row["S11"]));
_data.Add((double)Convert.ToDouble(row["S12"]));
_data.Add((double)Convert.ToDouble(row["S13"]));
_data.Add((double)Convert.ToDouble(row["S14"]));
_data.Add((double)Convert.ToDouble(row["S15"]));
_data.Add((double)Convert.ToDouble(row["S21"]));
_data.Add((double)Convert.ToDouble(row["S22"]));
_data.Add((double)Convert.ToDouble(row["S23"]));
_data.Add((double)Convert.ToDouble(row["S24"]));
_data.Add((double)Convert.ToDouble(row["S25"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data);
Response.Write(chartData);
}
private void GetData()
{
StringBuilder str = new StringBuilder();
SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=MyData;Integrated Security=SSPI");
SqlDataAdapter adp = new SqlDataAdapter("select top 1 * from MyTable order by Id desc ", con);
adp.Fill(dt);
}
}
HTML (.aspx) Code
<script src="JavaScript/highcharts.js"></script>
<script src="JavaScript/exporting.js"></script>
<div id="container" style="min-width: 280px; height: 400px; margin: 0 auto"></div>

Related

Simplify JavaScript array variable

I'm looking to simplify this code. Any way to it so? Spring MVC + Apex Charts
var d = /*[[${s0}]]*/ null`; <-- It is sent via the Spring Framework. Basically represents datetime(in millis) at `d[0]`, `d[3]`,... Temperature at `d[1]`, `d[4]`,... and Humidity at `d[2]`, `d[5]`,...
<script type="text/javascript" th:inline="javascript">
var d = /*[[${s0}]]*/ null;
var options = {
chart: {
type: 'area',
height: 300
},
series: [
{
name: 'Temperature',
data: [
[d[0], d[1]],
[d[3], d[4]],
[d[6], d[7]],
[d[9], d[10]],
[d[12], d[13]],
[d[15], d[16]],
[d[18], d[19]],
[d[21], d[22]],
[d[24], d[25]],
[d[27], d[28]],
[d[30], d[31]],
[d[33], d[34]],
[d[36], d[37]],
[d[39], d[40]],
[d[42], d[43]],
[d[45], d[46]],
[d[48], d[49]],
[d[51], d[52]],
[d[54], d[55]],
[d[57], d[58]],
[d[60], d[61]],
[d[63], d[64]],
[d[66], d[67]],
[d[69], d[70]]
]
},
{
name: "Humidity",
data: [
[d[0], d[2]],
[d[3], d[5]],
[d[6], d[8]],
[d[9], d[11]],
[d[12], d[14]],
[d[15], d[17]],
[d[18], d[20]],
[d[21], d[23]],
[d[24], d[26]],
[d[27], d[29]],
[d[30], d[32]],
[d[33], d[35]],
[d[36], d[38]],
[d[39], d[41]],
[d[42], d[44]],
[d[45], d[47]],
[d[48], d[50]],
[d[51], d[53]],
[d[54], d[56]],
[d[57], d[59]],
[d[60], d[62]],
[d[63], d[65]],
[d[66], d[68]],
[d[69], d[71]]
]
}
],
xaxis: {
type: 'datetime'
},
yaxis: [
{
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Temperature"
}
}, {
min: 0,
max: 100,
opposite: true,
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Humidity"
}
}
],
legend: {
position: 'top',
horizontalAlign: 'center'
},
tooltip: {
x: {
format: 'HH:mm dd/MM/yy'
},
}
}
var chart = new ApexCharts(document.querySelector("#chart0"), options);
chart.render();
</script>
I just need to simplify sending data via d[0], d[1] etc. Is there any kind of loop or anything else I can use?
You could take a function which takes the data and a pattern for the wanted elements and an offset for increment for the next row.
function mapByPattern(data, pattern, offset) {
var result = [], i = 0;
while (i < data.length) {
result.push(pattern.map(j => data[i + j]));
i += offset;
}
return result;
}
var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
result = { series: [
{ name: 'Temperature', data: mapByPattern(data, [0, 1], 3) },
{ name: "Humidity", data: mapByPattern(data, [0, 2], 3) }
]};
console.log(result);
Thank You, Nina. Code code didn't work exactly as i wanted but was so helpful to fix my own. Thanks alot! Here's some fixed code :)
var data = /*[[${s0}]]*/ null;
function mapByPattern(data, pattern, offset) {
var result = [], i = 0;
while (i < data.length) {
result.push(pattern.map(j => data[i + j]));
i += offset;
}
return result;
}
var options = {
chart: {
type: 'area',
height: 300
},
series: [
{
name: 'Temperature',
data: mapByPattern(data, [0, 1], 3)
},
{
name: "Humidity",
data: mapByPattern(data, [0, 2], 3)
}
],
xaxis: {
type: 'datetime'
},
yaxis: [
{
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Temperature"
}
}, {
min: 0,
max: 100,
opposite: true,
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Humidity"
}
}
],
legend: {
position: 'top',
horizontalAlign: 'center'
},
tooltip: {
x: {
format: 'HH:mm dd/MM/yy'
},
}
}
var chart = new ApexCharts(document.querySelector("#chart0"), options);
chart.render();

Highcharts load data from server ok, but not updating

I load succesfully from database but then it doesn't update dynamic. The function InitHighchart produce Highchart and I am trying to update series using requestData function
function requestData() {
$.ajax({
url: 'http://....url.../json.php',
data: {region:region},
type: 'post',
dataType: 'json',
error: function (point) {
var series = chart.series[0],
shift = series.data.length > 50; // shift if the series is longer than 20
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
success: function (point) {
var series = chart.series[1],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
cache: false
});
}
and here the chart
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script>
//is it right here to define chart?
var chart; // global
var region = "<?php Print($region); ?>";
function requestData() {
$.ajax({
url: 'http://cstation.admie.gr/iREACT_cSTATION_WEB/trexousa_katastasi/json.php',
data: {region:region},
type: 'post',
dataType: "json",
error: function (point) {
var series = chart.series[0],
shift = series.data.length > 50; // shift if the series is longer than 20
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
success: function (point) {
var series = chart.series[1],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
cache: false
});
}
function InitHighChart()
{
$("#chart1").html('LOADING');
var options =
{
chart: {
renderTo: 'chart1',
borderColor: '#a1a1a1',
borderRadius: 13,
alignTicks: false,
zoomType: 'xy',
height: 700,
events : {
load :requestData()
}
},
credits: {
enabled: false
},
title: {
text: "",
x: -50
},
xAxis: {
series: [{}],
labels: {
rotation: -75
}
},
yAxis: [{ //Primary yAxis
labels: {
format: '{value}',
style: {
color: "#000000"
}
},
title: {
text: '',
style: {
color: "#0B0EED"
}
}
}
],
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point)
{
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
//ajax call
$.ajax({
url: "http://...url.../json1.php",
data: {region:region},
type:'post',
dataType: "json",
success: function(data)
{
options.xAxis.categories = data.datetime;
options.series[0].name = 'Συνολικό Φορτίο (MWatt)';
options.series[0].data = data.SD_PData;
options.series[0].color = "#05A43C";
options.series[1].name = 'Συνολικό Φορτίο Φαινομένου (MVar)';
options.series[1].data = data.SD_MVAData;
options.series[1].color = "#EC2E03";
var chart = new Highcharts.Chart(options);
},
});
}
</script>
<!-- 3. Add the container -->
<div id="chart1" style="width: 1200px; height: 700px; margin: 0 auto"><body onload="InitHighChart()"></div>
Try this out. I have done the same thing in one of my code.
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'column'
},
title: {
text: 'Voting Results'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'votes'
}
},
series: [{}]
};
$.getJSON('votecount2.php', function(data) {
options.series[0].name = "Votes";
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
My JSON is this
[["Waseem Akhtar",5],["Imran Ismail",4],["Qaim Ali Shah",4]]

Kendo Panning Issue

I used the Kendo pan and zoom demos for this and the zoom works fine, but when I try panning the chart just clears out all data.
I am using remote data for this
Here I call the remote data using a datasource:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Home/GetActivities",
dataType: "json",
type: "POST"
}
},
group: "Group",
pageSize: viewSize,
page: 0
});
The drag handle and other variables:
//Maximum/Minimum number of visible items
var Min_Size = 5;
var Max_Size = 15;
//Minimum distance in px to start dragging
var Drag_Thr = 50;
//State variables
var viewStart = 0;
var viewSize = Min_Size;
var newStart;
function onDrag(e) {
var chart = e.sender;
var ds = chart.dataSource;
var delta = Math.round(e.originalEvent.x.initialDelta / Drag_Thr);
if (delta != 0) {
newStart = Math.max(0, viewStart - delta);
newStart = Math.min(dataSource.length - viewSize, newStart);
ds.query({
skip: newStart,
page: 0,
pageSize: viewSize
});
}
}
function onDragEnd() {
viewStart = newStart;
}
And finally my chart:
$("#chart").kendoChart({
theme: 'Metro',
title: { text: 'Activities' },
dataSource: dataSource,
legend: { visible: true, position: "top" },
series: [{ field: "Total", labels: { format: "{0}%", visible: true }, spacing: 0 }],
valueAxis: { labels: { format: "{0}%" }, line: { visible: false }, max: 100, min: 0 },
categoryAxis: { field: "Description", name: "Description", majorGridLines: { visible: false }, labels: { rotation: -90 } },
tooltip: { visible: false },
drag: onDrag,
dragEnd: onDragEnd,
zoom: onZoom
});
I'm not sure what is wrong and causing the drag to clear out the chart data.
Thanks in advance for your help

HighCharts dont get value

I try to see temperature history from sqlite database, but i don't get value from server side. I use node.js, socket.io and HighCharts library. I think, its client side problem. Server side:
io.sockets.on('connection', function(socket){
setInterval(function(){
var current_temp = db.all("SELECT * FROM (SELECT * FROM temp_irasai WHERE laikas ORDER BY laikas);",
function(err, rows){
if (err){
console.log('Error serving querying database. ' + err);
return;
}
data = {temp_irasai:[rows]};
socket.emit('istorija', data);
});
}, 5000);
});
Client side:
<script type="text/javascript">
var socket = io.connect('http://ip:3000');
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
zoomType: 'x',
spaceRight: 20,
events: {
load: function (){
socket.on('istorija', function(data){
var series = chart.series[0];
var i = 0;
while (data.temp_irasai[0][i])
{
series.data.push([data.temp_irasai[0][i].laikas, data.temp_irasai[0][i].laipsnis]);
i++;
}
chart.addSeries(series);
});
}
}
},
title: {
text: 'Temperatūra'
},
subtitle: {
text: 'Norint priartinti paspauskite ant grafiko ir pažymekite norimą plotą',
align: 'right',
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000,
title: {
text: 'Time',
margin: 15
}},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
showFirstLabel: false,
title: {
text: 'Temperatūra \u00B0C',
margin: 15
}},
plotOptions: {
area: {
fillColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, 'rgba(2,0,0,0)'],
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
},
},
series: [{
name: 'DS18B20 jutiklis (\u00B10.5\u00B0C)',
type: 'area',
data: []
}]
});
});
</script>
and database example:
CREATE TABLE temp_irasai(laikas integer PRIMARY KEY, laipsnis real);
INSERT INTO "temp_irasai" VALUES(1399533644551,20.4);
INSERT INTO "temp_irasai" VALUES(1399533646507,20.4);
INSERT INTO "temp_irasai" VALUES(1399533646547,20.4);
INSERT INTO "temp_irasai" VALUES(1399542709224,21.5);
COMMIT;
This part is just wrong:
load: function () {
socket.on('istorija', function (data) {
var series = chart.series[0];
var i = 0;
while (data.temp_irasai[0][i]) {
series.data.push([data.temp_irasai[0][i].laikas, data.temp_irasai[0][i].laipsnis]);
i++;
}
chart.addSeries(series);
});
}
You should add points, or use setData, like this:
load: function () {
socket.on('istorija', function (data) {
var series = chart.series[0];
var i = 0;
var d = [];
while (data.temp_irasai[0][i]) {
d.push([data.temp_irasai[0][i].laikas, data.temp_irasai[0][i].laipsnis]);
i++;
}
series.setData(d);
});
}
There is no data is given in your series set your values data in it, it will loads highcharts for sure, Good Luck!
type: 'area',
data: []
add Series data here.

Plotting json on .JS

I am trying to plot some json data but for some reason code is not workingLet me show my code.
My json looks like this:
{"d1":[[1356912000000, 1],[1356825600000, 1],[1356739200000, 1],[1356652800000, 1],[1356566400000, 38],[1356480000000, 47],[1356393600000, 1],[1356307200000, 4],[1356220800000, 1],[1356134400000, 2],[1356048000000, 50],[1355961600000, 51],[1327017600000, 38],[1326931200000, 52],[1326844800000, 45],[1326758400000, 49],[1326672000000, 46],[1326585600000, 1],[1326499200000, 5],[1326412800000, 44],[1326326400000, 48],[1326240000000, 43],[1326153600000, 46],[1326067200000, 41],[1325980800000, 1],[1325894400000, 4],[1325808000000, 45],[1325721600000, 43],[1325635200000, 42],[1325548800000, 42],[1325462400000, 43]]}
I am trying to plot with following code:
$(document).ready(function () {dashboard_A_chart.chartVisit ();});
dashboard_A_chart = {
chartVisit: function () {
var elem = $('#dashChartVisitors');
var options = {
colors: ["#edc240", "#5EB95E"],
legend: {
show: true,
noColumns: 2,
labelFormatter: null,
labelBoxBorderColor: false,
container: null,
margin: 8,
backgroundColor: false
},
xaxis: {
mode: "time",
font: {
weight: "bold"
},
color: "#D6D8DB",
tickColor: "rgba(237,194,64,0.25)",
min: "1325462400000",
max: "1356912000000",
tickLength: 5
},
selection: {
mode: "x"
},
};
var d1 = []
function onDataReceived(series) {d1 = [ series ];$.plot(elem, d1, options);}
$.ajax({
url: "../giga/data/dados1.json",
method: 'GET',
dataType: 'json',
success: onDataReceived
});
},
};
you are trying to call dashboard_A_chart.chartVisit() which is a function of an object literal which needs to be defined before.
you are creating the elem and options var inside the inside the chartVisit-function, but trying to use it in your onDataReceived-Function where it is not present.
it pretty much looks like you just copy & pasted some stuff together. take a looke at this code, that should work:
$(document).ready(function () {
var elem = $('#dashChartVisitors');
var options = {
colors: ["#edc240", "#5EB95E"],
legend: {
show: true,
noColumns: 2,
labelFormatter: null,
labelBoxBorderColor: false,
container: null,
margin: 8,
backgroundColor: false
},
xaxis: {
mode: "time",
font: {
weight: "bold"
},
color: "#D6D8DB",
tickColor: "rgba(237,194,64,0.25)",
min: "1325462400000",
max: "1356912000000",
tickLength: 5
},
selection: {
mode: "x"
}
};
$.ajax({
url: "../giga/data/dados1.json",
method: 'GET',
dataType: 'json',
success: function (data) {
$.plot(elem, data, options);
}
});
});

Categories

Resources