Chart Is not displaying Created Using HighCahrts and Google Analytics - javascript

I am using HighCharts to view data of Google Analytics. To get the data dynamically I use JSON. I have no doubts in that section. To do that I'm using the following JavaScript function.
function Load(responseJson){
//----------------------------------------------- Rohan
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = responseJson;
console.log("Row Data " + rowData)
console.log("RowData is " + typeof rowData );
inData = JSON.parse(rowData);
var count = 0;
var headers = new Array();
for (var i = 0; i < inData.columnHeaders.length; i++) {
headers[i] = inData.columnHeaders[i].name;
}
var dates = new Array();
var pageViews = new Array();
var uniqueViews = new Array();
for (var key in inData.rows) {
dates[key] = inData.rows[key][0];
pageViews[key] = parseInt(inData.rows[key][1]);
uniqueViews[key] = parseInt(inData.rows[key][2]);
}
$('#container_2').highcharts({
chart: {
type: 'areaspline', zoomType: 'x'
},
title: {
text: 'Pageviews and Bounces'
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 150,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#ffffff'
},
xAxis: {
categories: dates,
type: 'datetime',
dateTimeLabelFormats: {
month: '%d %b',
},
tickInterval: 10,
plotBands: [{ // visualize the weekend
color: 'rgba(68, 170, 213, .2)'
}]
},
yAxis: {
title: {
text: 'Visits'
}
},
tooltip: {
shared: true,
valueSuffix: ' '
},
credits: {
enabled: false
},
plotOptions: {
areaspline: {
fillOpacity: 0.5
}
},
series: [{
name: 'Page Views',
data: pageViews,
/***01***/colors: ['#CCFF99']
}, {
name: 'Bounces',
data: uniqueViews
}]
});
}
In this JavaScript fnction I managed to get the data from Google Analytics and pass to the chart that I have created using HighCharts. The chart does not displaying but when I put the mouse pointer on it shows the values. So I have tried to add some color to the series as in 01. But it did not change the appearance. Only the 2 Axis and the legend is showing but the colors are showing in the legend only. I can't figure it out what I have done wrong.
Could you someone please help me to solve this matter?
Thanks and regards,
Chiranthaka
Cleaned Source Code
function retStartDate(){
var strStartDate = document.getElementById("from_date").value;
return strStartDate;
}
function retEndDate(){
var strEndDate = document.getElementById("to_date").value;
return strEndDate;
}
function setJsonSer() {
var strWsUrl = 'https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A76546294&dimensions='+ 'ga%3Asource&metrics=ga%3Ausers&sort=-ga%3Ausers&start-date='+retStartDate()+'&end-date='+retEndDate()+'&max-results=10';
/*var strWsUrl = 'https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A76546294&dimensions=ga%3Asource&metrics=ga%3Ausers&filters=ga%3Asource!%3D(direct)&start-date='+retStartDate()+'&end-date='+retEndDate()+'&max-results=5';*/
formData = {
'Email': 'clientlink#client.com',
'Password': 'password',
'URL': strWsUrl
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
var responseText = data.responseText;
var responseJson = JSON.parse(responseText.match(/[{].*.[}]/));
console.log(responseJson);
Load(JSON.stringify(responseJson));
}
});
console.log("JSON The return is OK! ");
}
function BarChart(inData) {
var labels = new Array();
var values = new Array();
for (var key in inData.rows) {
var dt = new Array();
dt[0] = parseInt(inData.rows[key][1]);
var jsRow = { name: inData.rows[key][0], data: dt };
labels[key] = jsRow;
}
$(function () {
$('#container').highcharts({
chart: {
type: 'areaspline'
},
title: {
text: 'Which Source brought more users?'
},
subtitle: {
text: 'Source: Google Analytics'
},
xAxis: {
categories: ['Source'],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Number of Users',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: null
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: '#FFFFFF',
shadow: true
},
credits: {
enabled: false
},
series: labels
});
});
}
google.load('visualization', '1', { packages: ['table'] });
google.load("visualization", "1", { packages: ["corechart"] });
function Load(responseJson){
//----------------------------------------------- Rohan
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = responseJson;
console.log("Row Data " + rowData)
console.log("RowData is " + typeof rowData );
inData = JSON.parse(rowData);
var count = 0;
var headers = new Array();
for (var i = 0; i < inData.columnHeaders.length; i++) {
headers[i] = inData.columnHeaders[i].name;
}
var dates = new Array();
var pageViews = new Array();
var uniqueViews = new Array();
for (var key in inData.rows) {
dates[key] = inData.rows[key][0];
pageViews[key] = parseInt(inData.rows[key][1]);
uniqueViews[key] = parseInt(inData.rows[key][2]);
}
$('#container_2').highcharts({
chart: {
type: 'areaspline', zoomType: 'x'
},
title: {
text: 'Pageviews and Bounces'
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 150,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
xAxis: {
categories: dates,
type: 'datetime',
dateTimeLabelFormats: {
month: '%d %b',
},
tickInterval: 10,
plotBands: [{ // visualize the weekend
color: 'rgba(68, 170, 213, .2)'
}]
},
yAxis: {
title: {
text: 'Visits'
}
},
tooltip: {
shared: true,
valueSuffix: ' '
},
credits: {
enabled: false
},
plotOptions: {
areaspline: {
fillOpacity: 0.5
}
},
series: [{
name: 'Page Views',
data: pageViews,
color: '#ff0000'
}, {
name: 'Bounces',
data: uniqueViews,
color: '#ccff99'
}]
});
//----------------------------------------------- Rohan
//----------------------------------------------- Faahika
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = responseJson;
inData = JSON.parse(rowData);
var count = 0;
var headers = new Array();
for (var i = 1; i < inData.columnHeaders.length;i++) {
headers[i - 1] = inData.columnHeaders[i].name;
}
for (var key in inData.rows) {
var dt = new Array();
dt[0] = parseInt(inData.rows[key][1]);
dt[1] = parseInt(inData.rows[key][2]);
dt[2] = parseInt(inData.rows[key][3]);
arrayOfArray[count] = dt;
catogories[count] = inData.rows[key][0];
count++
}
var dynamicArray = new Array();
for (var i = 0; i < headers.length; i++) {
var temp = new Array();
for (var c = 0; c < arrayOfArray.length; c++) {
temp[c] = arrayOfArray[c][i];
}
dynamicArray[i] = temp;
}
var jsonCollection = new Array();
for (var c = 0; c < headers.length; c++) {
var json = { name: headers[c], data: dynamicArray[c] };
jsonCollection[c] = json;
}
console.log(jsonCollection);
$(function () {
$('#container_3').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Channels for Nurture Activities'
},
xAxis: {
categories: catogories
},
yAxis: {
min: 0,
title: {
text: null
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
shared: true
},
plotOptions: {
column: {
stacking: 'percent'
}
},
series:
jsonCollection
});
});
BarChart(inData);
DrawGoogleTable(NurtureActivities,[0,1,2,3,4],'table_div4',false);
DrawGoogleTable(ChannelNurtureActivities,[1,2],'table_div5',false);
DrawGoogleTable(TopSiteReferrers,[0,1],'table_div6',false);
DrawGoogleTable(TopCampaigns,[0,1],'table_div7',false);
DrawGoogleTable(TopKeywords,[0,1],'table_div8',false);
DrawGoogleTable(WebPages,[0,1],'table_div9',true);
DrawGoogleTable(ResearchDocuments,[0,1],'table_div11',false);
DrawGoogleTable(SocialNetworks,[0,1],'table_div10',false);
DrawGoogleTable(TopVideos,[0,1],'table_div12',false);
}
I have cleaned the code and deleted unwanted snippets. I have the problem in #container_2. But I passed data to #container_3 chart and it draw it perfectly. So could you someone look into the #container_2 chart? Thanks

I found the answer. The chart that I have used is using 2 data series but the the query string that I have used to draw the chart only consist one data series so the chart does not draw but only the legend and the 2 axis are drawing.
However thanks for everything guys!
Thanks and regards,
Chiranthaka

Related

Datetime in Y-Axis Highcharts

I'm in the middle of building heatmap chart, but i have problem adding datetime in Y axis from timestamp data in my json file, it just showing 00:00:00:001 in my Y axis chart.
This is my code
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'heatmap'
},
xAxis: {
tickPixelInterval: 1000,
categories: []
},
yAxis: {
type: 'datetime'
},
legend: {
align: 'right',
layout: 'vertical',
margin: 0,
verticalAlign: 'top',
symbolHeight: 280
},
colorAxis: {
stops: [
[0, '#3060cf'],
[0.5, '#fffbbc'],
[0.9, '#c4463a']
],
min: -5
},
plotOptions: {
series: {
turboThreshold: 0
}
},
series: [{
dataLabels: {
enabled: true,
color: '#000000'
}
}]
};
var ajaxCounter = 0,
dataArr = [],
intervalId = setInterval(function() {
$.getJSON('test.json', function(data) {
var categories = [],
prevCat = -1,
numb = -1;
Highcharts.each(data, function(xvals, i) {
if (prevCat !== xvals[0]) {
numb++;
prevCat = xvals[0];
categories.push((xvals[0]));
dataArr.push([numb, ajaxCounter, xvals[2]]);
} else {
dataArr.push([numb, ajaxCounter, xvals[2]]);
}
});
ajaxCounter++;
options.xAxis.categories = categories;
options.series[0].data = dataArr;
var chart = new Highcharts.Chart(options);
if (ajaxCounter === 24) {
clearInterval(intervalId);
}
});
}, 10000);
});
This is my json file
[
[100,1474633760,0],
[200,1474633760,0],
[300,1474633760,2471.0],
[400,1474633760,0],
[500,1474633760,0],
[600,1474633760,1951.0],
[700,1474633760,0],
[800,1474633760,0],
[900,1474633760,2125.0],
[1000,1474633760,0]
]
Thank you for you attention, i hope you guys can help my little project

Want to take difference between single series data and show them on chart in highcharts/highstock

I am working on asp.net MVC 5
Referring to my question i want to take difference between each two points like this 2-1 3-2 4-3 5-4 and so on and then put them into my series data in chart
Bellow is my controller code
//Getting data from DB to view in charts
SqlCommand Device_Id_command = new SqlCommand("Select Device_ID, Energy_kWh,Power_kW,Voltage_Phase_1,Data_Datetime,Voltage_Phase_2,Voltage_Phase_3,Current_Phase_1,Current_Phase_2,Current_Phase_3 from [ADS_Device_Data] where Device_Serial_Number=#serial_number AND Data_Datetime between'" + time.ToString(format) + "'AND'" + time2.ToString(format) + "'", con);
Device_Id_command.Parameters.AddWithValue("#serial_number", serial_number);
con.Open();
SqlDataReader reader = Device_Id_command.ExecuteReader();
//SqlDataReader reader_events = event_command.ExecuteReader();
while (reader.Read())
{
energy_kwh.Add(Convert.ToDouble(reader["Energy_kWh"]));
power_kw.Add(Convert.ToDouble(reader["Power_kW"]));
voltage_1.Add(Convert.ToDouble(reader["Voltage_Phase_1"]));
voltage_2.Add(Convert.ToDouble(reader["Voltage_Phase_2"]));
voltage_3.Add(Convert.ToDouble(reader["Voltage_Phase_3"]));
current_1.Add(Convert.ToDouble(reader["Current_Phase_1"]));
current_2.Add(Convert.ToDouble(reader["Current_Phase_2"]));
current_3.Add(Convert.ToDouble(reader["Current_Phase_3"]));
Meter_datetime.Add(sample_con.ConvertToUnixTimestamp(Convert.ToDateTime(reader["Data_Datetime"])));
device_id = Convert.ToInt32(reader["Device_ID"]);
}
con.Close();
After that i have put all the data coming from reader into ViewData
ViewData["energy_kwh"] = energy_kwh;
ViewData["Meter_datetime"] = Meter_datetime;
ViewData["power_kw"] = power_kw;
ViewData["voltage_1"] = voltage_1;
ViewData["voltage_2"] = voltage_2;
ViewData["voltage_3"] = voltage_3;
ViewData["current_1"] = current_1;
ViewData["current_2"] = current_2;
ViewData["current_3"] = current_3;
In my razor i have done the following
// **************** Data arranging coming from controller *************
var myArrayX_kwh = [];
var myArrayY_kwh = [];
var myArrayY_power = [];
var myArrayY_voltage_1 = [];
var myArrayY_voltage_2 = [];
var myArrayY_voltage_3 = [];
var myArrayY_current_1 = [];
var myArrayY_current_2 = [];
var myArrayY_current_3 = [];
//var myArrayY_getData = [];
var arry_kwh = [];
var arry_power = [];
var arry_voltage_1 = [];
var arry_voltage_2 = [];
var arry_voltage_3 = [];
var arry_current_1 = [];
var arry_current_2 = [];
var arry_current_3 = [];
After that i have added 2 loops which push the values of x and y axis
#foreach (var st in ViewData["Meter_datetime"] as List<double?>)
{
#:myArrayX_kwh.push(#st);
}
#foreach (var st in ViewData["energy_kwh"] as List<double?>)
{
#:myArrayY_kwh.push(#st);
}
#foreach (var st in ViewData["power_kw"] as List<double?>)
{
#:myArrayY_power.push(#st);
}
#foreach (var st in ViewData["voltage_1"] as List<double?>)
{
#:myArrayY_voltage_1.push(#st);
}
#foreach (var st in ViewData["voltage_2"] as List<double?>)
{
#:myArrayY_voltage_2.push(#st);
}
#foreach (var st in ViewData["voltage_3"] as List<double?>)
{
#:myArrayY_voltage_3.push(#st);
}
#foreach (var st in ViewData["current_1"] as List<double?>)
{
#:myArrayY_current_1.push(#st);
}
#foreach (var st in ViewData["current_2"] as List<double?>)
{
#:myArrayY_current_2.push(#st);
}
#foreach (var st in ViewData["current_3"] as List<double?>)
{
#:myArrayY_current_3.push(#st);
}
for (var i = 0; i < myArrayX_kwh.length; i++) {
arry_kwh.push({ x: myArrayX_kwh[i], y: myArrayY_kwh[i], });
arry_power.push({ x: myArrayX_kwh[i], y: myArrayY_power[i], });
arry_voltage_1.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_1[i], });
arry_voltage_2.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_2[i], });
arry_voltage_3.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_3[i], });
arry_current_1.push({ x: myArrayX_kwh[i], y: myArrayY_current_1[i], });
arry_current_2.push({ x: myArrayX_kwh[i], y: myArrayY_current_2[i], });
arry_current_3.push({ x: myArrayX_kwh[i], y: myArrayY_current_3[i], });
//getData.push({y: myArrayY_getData[i] });
}
After that i have initialized my chart
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1',
type: 'column',
zoomType: 'xy',
panning: true,
panKey: 'shift',
//type: 'column',
//zoomType: 'xy',
//panning: true,
//pankey: 'shift',
resetZoomButton: {
position: {
//align: 'right', // by default
//verticalAlign: 'top', // by default
x: -10,
y: 350,
//height: 25
},
relativeTo: 'chart'
}
},
scrollbar:{
enabled: true
},
navigator: {
//xAxis: {
// tickWidth: 0,
// lineWidth: 0,
// gridLineWidth: 1,
// tickPixelInterval: 200,
// labels: {
// align: 'left',
// style: {
// color: '#888'
// },
// x: 3,
// y: -4
// }
//},
//yAxis: {
// gridLineWidth: 0,
// startOnTick: false,
// endOnTick: false,
// minPadding: 0.1,
// maxPadding: 0.1,
// labels: {
// enabled: false
// },
// title: {
// text: null
// },
// tickWidth: 0
//},
//series: {
// //data: arry_kwh_2,
// type: 'column',
// color: '#4572A7',
// fillOpacity: 0.05,
// dataGrouping: {
// smoothed: true
// },
// lineWidth: 1,
// marker: {
// enabled: true
// }
//},
enabled: true,
height: 30,
},
rangeSelector: {
buttonTheme: { // styles for the buttons
fill: 'none',
stroke: 'none',
'stroke-width': 0,
r: 8,
style: {
color: '#039',
fontWeight: 'bold'
},
states: {
hover: {
},
select: {
fill: '#039',
style: {
color: 'white'
}
}
}
},
enabled: true,
inputBoxWidth: 160,
inputStyle: {
color: '#039',
fontWeight: 'bold'
},
labelStyle: {
color: 'black',
fontWeight: 'bold'
},
buttons: [{
type: 'minute',
count: 60 * 6,
text: '6h'
}, {
type: 'day',
count: 1,
text: '1d'
}, {
type: 'day',
count: 7,
text: '7d'
},
{
type: 'day',
count: 14,
text: '2w'
},
{
type: 'day',
count: 21,
text: '3w'
},
{
type: 'month',
count: 1,
text: '1m'
},
{
type: 'all',
text: 'All'
}]
},
plotOptions: {
column: {
turboThreshold: 500000
}
},
title: {
text: 'Energy vs Date & Time',
style: {
fontWeight: 'bold',
}
},
xAxis: {
type: 'datetime',
//min: 0,
//max: 100000
},
yAxis:
{
scrollbar: {
enabled: true,
showFull: false
},
alternateGridColor: '#FDFFD5',
title: {
text: 'Energy (kWh)',
style: {
//color: '#FF00FF',
fontSize: '12px',
//sfont: 'bold 200px Verdana, sans-serif',
}
}
},
series:
[
{
name: 'Energy kWh',
color: 'green',
data: arry_kwh,
}
],
});
Note
I am viewing 4 different charts in my single view
I only want to take difference for arry_kwh only not for all charts
Update
I have added this piece of code after that i have put this value of array into a separate series
var arry_kwh_diff = [];
for (var j = 0; j < arry_kwh.length - 1; j++)
{
arry_kwh_diff[j] = { x: arry_kwh.x, y: arry_kwh[j + 1].y - arry_kwh[j].y };
}
arry_kwh_diff[j] = { x: arry_kwh.x, y: arry_kwh.y };
Adding the array in my chart code
series:
[
{
name: 'Energy kWh',
color: 'green',
data: arry_kwh,
},
{
type: 'spline',
name: 'Difference',
data: arry_kwh_diff
}
],
It's showing me bellow image
It's not showing me correct values also no spline is there
After changing
var arry_kwh_diff = [];
for (var j = 0; j < arry_kwh.length - 1; j++)
{
arry_kwh_diff.push({ x: arry_kwh[j].x, y: arry_kwh[j + 1].y - arry_kwh[j].y });
}
arry_kwh_diff[j] = { x: arry_kwh[j].x, y: arry_kwh[j].y };
Now it's showing me an empty view
Any help would be highly appreciated
You could prepare your data, before adding it to highcharts. For instance, do something like this:
var arry_kwh = [ {x: Date.now(), y: 100},
{x: Date.now()+1000, y: 120 },
{x: Date.now()+2000, y: 140 },
{x: Date.now()+3000, y: 165 }];
var arry_kwh_diff = [];
var i=0;
for(; i < arry_kwh.length - 1; i++) {
arry_kwh_diff[i] = {x: arry_kwh[i].x, y:arry_kwh[i+1].y - arry_kwh[i].y};
}
arry_kwh_diff[i] = {x: arry_kwh[i].x, y:arry_kwh[i].y};
And then use arry_kwh_diff to graph the difference.
A fiddle demo can be found here:
http://jsfiddle.net/8fjyLhy1/1/

HighChart isn't plotting data correctly

Hi I'm using high chart and the data is coming through okay however the date is not coming through on the x axis, I have a parameter in Data with the correctly formatted date and I'd like to use that on the x axis and popup, however I understand I need to use UTC datetime for it to order properly
https://imgur.com/32TyzvH
function buildAndUpdateTempChart() {
$.getJSON('server/getReadings.php', function (data) {
$('#chartContainer').highcharts('StockChart', {
chart:{
events: {
load: function(){
// set up the updating of the chart each second
//debugger;
// var series = this.series[0];
// //console.log('data is: ' + data);
// for(var i = 0; i < data.length - 1; i++){
// this.series[0].addPoint(data[i].temp, data[i].timestamp, true, true);
// this.series[1].addPoint(data[i].aTemp, data[i].timestamp, true, true);
// }
// setInterval(function () {
// //get tick
// var x = (new Date()).getTime(), // current time
// y = Math.round(Math.random() * 100);
// series.addPoint([x, y], true, true);
// }, 1000);
}
}
},
title: {
text: 'Temperature Sensor Readings'
},
yAxis: {
title: {
text: 'Degrees Celcius'
},
plotLines: [{
value: -10,
color: 'green',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Minimum tolerated.'
}
}, {
value: 20,
color: 'red',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Maximum tolerated.'
}
}]},
plotOptions: {
series: {
compare: 'percent'
}
},
series: [{
name: 'Temp',
data: (function () {
var temp = [];
for (var i = 0; i < data.length; i++) {
temp.push([
data[i].timestamp,
parseFloat(data[i].temp)
]);
}
return temp;
}()),
tooltip: {
valueDecimals: 2
}},
{
name: 'Ambient Temp',
data: (function () {
var aTemp = [];
for (var i = 0; i < data.length; i++) {
aTemp.push([
data[i].timestamp,
parseFloat(data[i].aTemp)
]);
}
return aTemp;
}()),
tooltip: {
valueDecimals: 2
},
}]
});
})
}
$(document).ready(function(){
buildAndUpdateTempChart(); //this is async so there rest of the app can continue to work
});
My guess is you need
xAxis: {
type: 'datetime'
},
in your code. Hope this helps.
this could help you, you have to specify xAxis a datetime
function buildAndUpdateTempChart() {
$.getJSON('server/getReadings.php', function (data) {
$('#chartContainer').highcharts('StockChart', {
chart:{
events: {
load: function(){
// set up the updating of the chart each second
//debugger;
// var series = this.series[0];
// //console.log('data is: ' + data);
// for(var i = 0; i < data.length - 1; i++){
// this.series[0].addPoint(data[i].temp, data[i].timestamp, true, true);
// this.series[1].addPoint(data[i].aTemp, data[i].timestamp, true, true);
// }
// setInterval(function () {
// //get tick
// var x = (new Date()).getTime(), // current time
// y = Math.round(Math.random() * 100);
// series.addPoint([x, y], true, true);
// }, 1000);
}
}
},
title: {
text: 'Temperature Sensor Readings'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Degrees Celcius'
},
plotLines: [{
value: -10,
color: 'green',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Minimum tolerated.'
}
}, {
value: 20,
color: 'red',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Maximum tolerated.'
}
}]},
plotOptions: {
series: {
compare: 'percent'
}
},
series: [{
name: 'Temp',
data: (function () {
var temp = [];
for (var i = 0; i < data.length; i++) {
temp.push([
data[i].timestamp,
parseFloat(data[i].temp)
]);
}
return temp;
}()),
tooltip: {
valueDecimals: 2
}},
{
name: 'Ambient Temp',
data: (function () {
var aTemp = [];
for (var i = 0; i < data.length; i++) {
aTemp.push([
data[i].timestamp,
parseFloat(data[i].aTemp)
]);
}
return aTemp;
}()),
tooltip: {
valueDecimals: 2
},
}]
});
})
}
$(document).ready(function(){
buildAndUpdateTempChart(); //this is async so there rest of the app can continue to work
});

Counting json data to create dynamic series in highchart line charts

I've got Json data like this :
q_table.php
[{"data":["2012-12-16; 0","2012-12-16; 23"]},{"name":"MSMDN1","data":[98.9914,99.5429]},{"name":"MSMDN2","data":[99.4577,99.5078]},{"name":"MSMDN3","data":[99.1454,99.4605]},{"name":"MSMDN4","data":[98.9663,99.3663,]},{"name":"MSMDN5","data":[104.97,91.4251]}]
I want to count the array data so the data look like this:
json_data = [0]; //data":["2012-12-16; 0","2012-12-16; 23"]
json_data = [1]; //"name":"MSMDN1","data":[98.9914,99.5429]
json_data = [2]; //"name":"MSMDN2","data":[99.4577,99.5078]
json_data = [3]; //"name":"MSMDN3","data":[99.1454,99.4605]
json_data = [4]; //"name":"MSMDN4","data":[98.9663,99.3663,]
json_data = [5]; //"name":"MSMDN5","data":[104.97,91.4251]}
How to counting those array from javascript?
This code below was worked, but as you see at the script part that get json data, i must declare series and categories manually
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 155
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [''],
labels:
{
rotation: -90
}
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("q_table.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
options.series[4] = json[5];
//options.series[5] = json[6];
chart = new Highcharts.Chart(options);
});
});
Here is the script part that i change according to #SebastianBochan answer
$.getJSON("q_table.php", function(json)
{
var len = json.length
for(i=0;i<len;i++){
if(i===0){
options.xAxis.categories = json[i]['data'];
}else{
j = i-1;
options.series[j] = json[i];
}
}
chart = new Highcharts.Chart(options);
});
or any other way, very pleased..
Worked Script
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 155
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [''],
labels:
{
rotation: -90
}
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("q_table.php", function(json)
{
var len = json.length
for(i=0;i<len;i++){
if(i===0){
options.xAxis.categories = json[i]['data'];
}else{
j = i-1;
options.series[j] = json[i];
}
}
chart = new Highcharts.Chart(options);
});
});
You need to parse check which line should be categories and which series. I simulated json as variable Take look:
var json = [{
"data": ["2012-12-16; 0", "2012-12-16; 23"]
}, {
"name": "MSMDN1",
"data": [98.9914, 99.5429]
}, {
"name": "MSMDN2",
"data": [99.4577, 99.5078]
}, {
"name": "MSMDN3",
"data": [99.1454, 99.4605]
}, {
"name": "MSMDN4",
"data": [98.9663, 99.3663]
}, {
"name": "MSMDN5",
"data": [104.97, 91.4251]
}];
var len = json.length
i = 0;
var options = {
xAxis: {
categories: []
},
series: []
}
for (i; i < len; i++) {
if (i === 0) {
var dat = json[i].data,
lenJ = dat.length,
j = 0,
tmp;
for (j; j < lenJ; j++) {
tmp = dat[j].split(';');
options.xAxis.categories.push(tmp[0]);
}
} else {
options.series.push(json[i]);
}
}
http://jsfiddle.net/UKfPm/
$.getJSON("q_table.php", function(json)
var options = {}; // whatever options you want to set, at least the container
options.series = new Array();
for(i=0;i< json.length;i++) {
options.series.push(json[i]);
}
chart = new Highcharts.Chart(options);
});

Link multiple chart controls in HighCharts

On my web page i'm displaying 5 different line charts with a zoomable X axis. Each chart also has a number of series that are the same for all the charts.
Im looking for the the controls where you can show/hide a series and zoom feature to happen within each graph no matter which graphs controls I change.
Is this something Highcharts support?
Please familiar with example which synchronizes three charts and have unzoom button.
$(function() {
var chart1;
var chart2;
var chart3;
var controllingChart;
var defaultTickInterval = 5;
var currentTickInterval = defaultTickInterval;
$(document).ready(function() {
function unzoom() {
chart1.options.chart.isZoomed = false;
chart2.options.chart.isZoomed = false;
chart3.options.chart.isZoomed = false;
chart1.xAxis[0].setExtremes(null, null);
chart2.xAxis[0].setExtremes(null, null);
chart3.xAxis[0].setExtremes(null, null);
}
//catch mousemove event and have all 3 charts' crosshairs move along indicated values on x axis
function syncronizeCrossHairs(chart) {
var container = $(chart.container),
offset = container.offset(),
x, y, isInside, report;
container.mousemove(function(evt) {
x = evt.clientX - chart.plotLeft - offset.left;
y = evt.clientY - chart.plotTop - offset.top;
var xAxis = chart.xAxis[0];
//remove old plot line and draw new plot line (crosshair) for this chart
var xAxis1 = chart1.xAxis[0];
xAxis1.removePlotLine("myPlotLineId");
xAxis1.addPlotLine({
value: chart.xAxis[0].translate(x, true),
width: 1,
color: 'red',
//dashStyle: 'dash',
id: "myPlotLineId"
});
//remove old crosshair and draw new crosshair on chart2
var xAxis2 = chart2.xAxis[0];
xAxis2.removePlotLine("myPlotLineId");
xAxis2.addPlotLine({
value: chart.xAxis[0].translate(x, true),
width: 1,
color: 'red',
//dashStyle: 'dash',
id: "myPlotLineId"
});
var xAxis3 = chart3.xAxis[0];
xAxis3.removePlotLine("myPlotLineId");
xAxis3.addPlotLine({
value: chart.xAxis[0].translate(x, true),
width: 1,
color: 'red',
//dashStyle: 'dash',
id: "myPlotLineId"
});
//if you have other charts that need to be syncronized - update their crosshair (plot line) in the same way in this function.
});
}
//compute a reasonable tick interval given the zoom range -
//have to compute this since we set the tickIntervals in order
//to get predictable synchronization between 3 charts with
//different data.
function computeTickInterval(xMin, xMax) {
var zoomRange = xMax - xMin;
if (zoomRange <= 2)
currentTickInterval = 0.5;
if (zoomRange < 20)
currentTickInterval = 1;
else if (zoomRange < 100)
currentTickInterval = 5;
}
//explicitly set the tickInterval for the 3 charts - based on
//selected range
function setTickInterval(event) {
var xMin = event.xAxis[0].min;
var xMax = event.xAxis[0].max;
computeTickInterval(xMin, xMax);
chart1.xAxis[0].options.tickInterval = currentTickInterval;
chart1.xAxis[0].isDirty = true;
chart2.xAxis[0].options.tickInterval = currentTickInterval;
chart2.xAxis[0].isDirty = true;
chart3.xAxis[0].options.tickInterval = currentTickInterval;
chart3.xAxis[0].isDirty = true;
}
//reset the extremes and the tickInterval to default values
function unzoom() {
chart1.xAxis[0].options.tickInterval = defaultTickInterval;
chart1.xAxis[0].isDirty = true;
chart2.xAxis[0].options.tickInterval = defaultTickInterval;
chart2.xAxis[0].isDirty = true;
chart3.xAxis[0].options.tickInterval = defaultTickInterval;
chart3.xAxis[0].isDirty = true;
chart1.xAxis[0].setExtremes(null, null);
chart2.xAxis[0].setExtremes(null, null);
chart3.xAxis[0].setExtremes(null, null);
}
$(document).ready(function() {
$('#btn').click(function(){
unzoom();
});
var myPlotLineId = "myPlotLine";
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
zoomType: 'x',
//x axis only
borderColor: '#003399',
//'#022455',
borderWidth: 1,
isZoomed:false
},
title: {
text: 'Height Versus Weight'
},
subtitle: {
text: 'Source: Notional Test Data'
},
xAxis: {
title: {
enabled: true,
text: 'Height (cm)'
},
tickInterval:5,
startOnTick: true,
endOnTick: true,
showLastLabel: true,
events:{
afterSetExtremes:function(){
if (!this.chart.options.chart.isZoomed)
{
var xMin = this.chart.xAxis[0].min;
var xMax = this.chart.xAxis[0].max;
var zmRange = computeTickInterval(xMin, xMax);
chart1.xAxis[0].options.tickInterval =zmRange;
chart1.xAxis[0].isDirty = true;
chart2.xAxis[0].options.tickInterval = zmRange;
chart2.xAxis[0].isDirty = true;
chart3.xAxis[0].options.tickInterval = zmRange;
chart3.xAxis[0].isDirty = true;
chart2.options.chart.isZoomed = true;
chart3.options.chart.isZoomed = true;
chart2.xAxis[0].setExtremes(xMin, xMax, true);
chart3.xAxis[0].setExtremes(xMin, xMax, true);
chart2.options.chart.isZoomed = false;
chart3.options.chart.isZoomed = false;
}
}
}
},
yAxis: {
title: {
text: 'Weight (kg)'
}
},
tooltip: {
formatter: function() {
return '' + this.x + ' km, ' + this.y + ' km';
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
backgroundColor: '#FFFFFF',
borderWidth: 1
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
}
}
},
series: [{
name: 'Group 1',
color: 'rgba(223, 83, 83, .5)',
data: [[146.2, 51.6], [147.5, 59.0], [148.5, 49.2], [151.0, 63.0], [155.8, 53.6],
[157.0, 59.0], [159.1, 47.6], [161.0, 69.8], [166.2, 66.8], [168.2, 75.2],
[172.5, 55.2], [174.9, 54.2], [176.9, 62.5], [180.4, 42.0], [190.0, 50.0]]
},
{
name: 'dummy_data',
//put this in so that x axis is consistent between 3 charts to begin with
color: 'rgba(119, 152, 191, .5)',
showInLegend: false,
data: [[145.0, 0.0], [200.0, 0.0]]}]
}, function(chart) { //add this function to the chart definition to get synchronized crosshairs
syncronizeCrossHairs(chart);
});
chart2 = new Highcharts.Chart({
chart: {
renderTo: 'container2',
type: 'line',
zoomType: 'x',
//x axis only
borderColor: '#003399',
//'#022455',
borderWidth: 1,
isZoomed:false
/*events: {
selection: function(event) { //this function should zoom chart1, chart2, chart3 according to selected range
controllingChart = "chart2";
setTickInterval(event);
}
}*/
},
title: {
text: 'Height Versus Weight'
},
subtitle: {
text: 'Source: Notional Test Data'
},
xAxis: {
title: {
enabled: true,
text: 'Height (cm)'
},
tickInterval:5,
startOnTick: true,
endOnTick: true,
showLastLabel: true,
events: {
afterSetExtremes: function() {
if (!this.chart.options.chart.isZoomed)
{
var xMin = this.chart.xAxis[0].min;
var xMax = this.chart.xAxis[0].max;
var zmRange = computeTickInterval(xMin, xMax);
chart1.xAxis[0].options.tickInterval =zmRange;
chart1.xAxis[0].isDirty = true;
chart2.xAxis[0].options.tickInterval = zmRange;
chart2.xAxis[0].isDirty = true;
chart3.xAxis[0].options.tickInterval = zmRange;
chart3.xAxis[0].isDirty = true;
chart1.options.chart.isZoomed = true;
chart3.options.chart.isZoomed = true;
chart1.xAxis[0].setExtremes(xMin, xMax, true);
chart3.xAxis[0].setExtremes(xMin, xMax, true);
chart1.options.chart.isZoomed = false;
chart3.options.chart.isZoomed = false;
}
}
}
},
yAxis: {
title: {
text: 'Weight (kg)'
}
},
tooltip: {
formatter: function() {
return '' + this.x + ' km, ' + this.y + ' km';
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
backgroundColor: '#FFFFFF',
borderWidth: 1
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
}
}
},
series: [{
name: 'dummy_data',
color: 'rgba(223, 83, 83, .5)',
showInLegend: false,
data: [[145.0, 0.0], [200.0, 0.0]]},
{
name: 'Group 2',
color: 'rgba(119, 152, 191, .5)',
data: [[151.0, 65.6], [166.3, 71.8], [167.5, 80.7], [168.5, 72.6], [172.2, 78.8],
[174.5, 74.8], [175.0, 86.4], [181.5, 78.4], [182.0, 62.0], [184.0, 81.6],
[185.0, 76.6], [186.8, 83.6], [186.0, 90.0], [188.0, 74.6], [190.0, 71.0],
[192.0, 79.6], [193.7, 93.8], [196.5, 70.0], [199.0, 72.4]]}]
}, function(chart) { //add this function to the chart definition to get synchronized crosshairs
//this function needs to be added to each syncronized chart
syncronizeCrossHairs(chart);
});
chart3 = new Highcharts.Chart({
chart: {
renderTo: 'container3',
type: 'line',
zoomType: 'x',
//x axis only
borderColor: '#003399',
//'#022455',
borderWidth: 1,
isZoomed:false
/*events: {
selection: function(event) { //this function should zoom chart1, chart2, chart3
controllingChart = "chart3";
setTickInterval(event);
}
}*/
},
title: {
text: 'Height Versus Weight'
},
subtitle: {
text: 'Source: Notional Test Data'
},
xAxis: {
title: {
enabled: true,
text: 'Height (cm)'
},
tickInterval:5,
startOnTick: true,
endOnTick: true,
showLastLabel: true,
events: {
afterSetExtremes: function() {
if (!this.chart.options.chart.isZoomed) {
var xMin = this.chart.xAxis[0].min;
var xMax = this.chart.xAxis[0].max;
var zmRange = computeTickInterval(xMin, xMax);
chart1.xAxis[0].options.tickInterval =zmRange;
chart1.xAxis[0].isDirty = true;
chart2.xAxis[0].options.tickInterval = zmRange;
chart2.xAxis[0].isDirty = true;
chart3.xAxis[0].options.tickInterval = zmRange;
chart3.xAxis[0].isDirty = true;
chart1.options.chart.isZoomed = true;
chart2.options.chart.isZoomed = true;
chart1.xAxis[0].setExtremes(xMin, xMax, true);
chart2.xAxis[0].setExtremes(xMin, xMax, true);
chart1.options.chart.isZoomed = false;
chart2.options.chart.isZoomed = false;
}
}
}
},
yAxis: {
title: {
text: 'Weight (kg)'
}
},
tooltip: {
formatter: function() {
return '' + this.x + ' km, ' + this.y + ' km';
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
backgroundColor: '#FFFFFF',
borderWidth: 1
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
}
}
},
series: [{
name: 'dummy_data',
//I put this in to try to get the charts to have the same range on the x axis
color: 'rgba(223, 83, 83, .5)',
showInLegend: false,
data: [[145.0, 0.0], [200.0, 0.0]]},
{
name: 'Group 3',
color: 'rgba(119, 152, 191, .5)',
data: [[153.0, 65.6], [156.3, 71.8], [167.5, 80.7], [169.5, 72.6], [171.2, 78.8],
[172.5, 74.8], [177.0, 86.4], [181.5, 78.4], [183.0, 62.0], [184.0, 81.6],
[185.0, 76.6], [186.2, 83.6], [187.0, 90.0], [188.7, 74.6], [190.0, 71.0],
[192.0, 79.6], [195.7, 93.8], [196.5, 70.0], [199.4, 72.4]]}]
}, function(chart) { //add this function to the chart definition to get synchronized crosshairs
//this function needs to be added to each syncronized chart
syncronizeCrossHairs(chart);
});
});
});
});
http://jsfiddle.net/Gv7Tg/27/
There are two possible solutions:
The easiest option would be to show/hide and zoom with extra buttons.
So you would add some buttons to your page and execute a function like:
//Edit made a mistake selecting the chart:
You should create your chart and add it to the Array when you are creating it. For example:
var charts = new Array();
var chart = new Highcharts.StockChart(opts);
charts.push(chart);
Then for the function:
//Set xAxis extremes (zoom)
for (var i = 0; i < charts.length; i++) {
charts[i].xAxis[0].setExtremes(startDate, endDate);
}
to change the zoom.
Showing and hiding of a series is also pretty simple:
Highstock Options Reference
So you could just call charts[i].series[0].hide(); to hide the first Series
Another possibility would be to use the Highcharts events to start a similar function when a user clicks on the chart.
For example on the legend: Highstock Options Reference
And for the Zoom:
xAxis : {
events : {
afterSetExtremes : afterSetExtremes
},
},

Categories