I am trying to display csv data in the tooltip of the Highcharts.
Data:
Time,Users,AVG_Sec,Volume,ServerName,InstanceName
11:35 AM ,59,.863,664,server1,int123
11:35 AM ,43,.659,392,server2,int123
11:35 AM ,46,1.347,442,server3,int124
11:35 AM ,49,1.164,702,server2,int125
I am able to display users,avg_sec and volume in the graph.
Please let me know if i can dsplay the servername and instance name in the graph as bars/columns else at least show them in tool tip.
The code so far:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Last Hourly All'
},
tooltip:{
formatter:function(){
return '<b>' + this.series.name + '</b>' +
'<br/><b>X Value:</b> ' + this.x +
'<br/><b>Y Value:</b> ' + this.y +
'<br/><b>Other Data:</b> ' + this.point.ServerName;
}
},
credits: {
enabled: false
},
xAxis: {
categories: [],
labels: {
rotation: -90
}
},
yAxis:[{
startOnTick: false,
title: {
text: 'No of Transactions'
}
}, {
opposite: true,
title: {
text: 'Response Time'
}
}, {
opposite: true,
title: {
text: 'Volume'
}
}, {
opposite: true,
title: {
text: 'Server Name'
}
}, {
opposite: true,
title: {
text: 'Instance Name'
}
}
],
series: []
};
//try.csv
$.get('data/lastHrlyAllTZ1.csv', function(data) {
// Split the lines
var lines = data.split('\n');
//variable declaration
var series = {
data: [],
type: 'spline',
color: '#336633'
};
var series1 = {
yAxis: 1,
data: [],
color: '#FF3399'
};
var series2 = {
yAxis: 2,
data: [],
color: '#9900FF'
};
var series3 = {
yAxis: 3,
data: [],
color: '#660066'
};
var series4 = {
yAxis: 4,
data: [],
color: '#CC99CC'
};
$.each(lines, function(lineNo, line) {
var items = line.split(',');
// header line contains categories
if (lineNo == 0) {
series1.name = items[1];
series.name = items[2];
series2.name = items[3];
series3.name = items[4];
series4.name = items[5];
}
// the rest of the lines contain data with their name in the first position
else {
$.each(items, function (itemNo, item) {
if (itemNo == 0) {
options.xAxis.categories.push(item);
} else if (itemNo == 1) {
//console.log(parseFloat(item));
series1.data.push(parseFloat(item));
} else if(itemNo == 2){
series.data.push(parseFloat(item));
} else if(itemNo == 3){
series2.data.push(parseFloat(item));
}
else if(itemNo == 4){
//alert(item);
series3.data.push(item);
}
else if(itemNo == 5){
series4.data.push(item);
}
});
}
});
options.series.push(series1);
options.series.push(series2);
options.series.push(series3);
options.series.push(series4);
options.series.push(series);
var chart = new Highcharts.Chart(options);
In the tool tip as of now it says "undefined".
It doesnt work, because you push only values into data array, but not define name of parametrs. You should push point as object, where you define name of your parameter and y value.
Related
I have a kendo grid in angular, which is supposed to have some columns with multi-select dropdown.
When I select the item from the list for the first time, that item gets binded and the second item when selected the gridParams holds the second item selected, but once the API call returns the data, the list binded refreshes to none(no data binded to the dropdownlist).
Below is the code related
{
OC.setReportGridColumns(responsecolumns);
OC.reportsGridOptions = {
dataSource: {
schema: {
data: "Data",
total: "Total",
model: {
fields: OC.GetSchemaFields()
}
},
transport: {
read: function (e) {
gridParams = JSON.parse(JSON.stringify({
CurrentPage: e.data.page,
PageSize: e.data.pageSize,
Sort: e.data.sort,
Filter: e.data.filter
}));
if (gridParams.Filter != undefined) {
var a;
if (gridParams.Filter.filters!= undefined) {
angular.forEach(gridParams.Filter.filters, function (value, key) {
if (value.field === "QuoteStatus") {
value.operator = "in";
a = "'" + value.value + "'";
a = a.replace(",", "','");
value.value = a;
}
});
};
};
ReportService.GetAllAdHocReport(gridParams, '', OC.CustomColumnSelected, TemplateId).then(function (response) {
if (response != '') {
$("li [ui- sref='AdHocReport']").parent().addClass("activelist");
response.Total = response.Data != null && response.Data.length > 0 ? response.Data[0].TotalRecords : 10;
OC.GridConfigDataSource.read();
e.success(response);
OC.hideFilters();
} else {
e.success([]);
}
});
},
},
filterable: {
mode: "row,menu",
extra:false
},
selectable: 'cell',
columns: OC.gridCols,
}
}
}
OC.setReportGridColumns = function (colList) {
var col = JSON.parse(colList).columns;
OC.setfilterDropdown(col);
var cols = col.map(function (value) {
if (value.column == "QuoteStatus") {
return {
field: value.column,
title: value.title,
filterable: OC.filterDropdowns(value.column),
width: value.width,
sortable: true,
};
}
});
}
OC.filterDropdowns = function (column) {
return {
extra: false,
mode: "menu",
multi: true,
cell: {
showOperators: false,
template: function (args) {
/////------****Multi-select Dropdown****------///////
args.element.kendoMultiSelect({
autoBind: true,
dataTextField: "text",
dataValueField: "value",
dataSource: new kendo.data.DataSource({
data: OC.getDataForFilterDropdown(column)
}),
index: 0,
optionLabel: {
text: "--Select--",
value: ""
},
valuePrimitive: true,
});
},
}
}
}
i use kendo grid for a data entry form. it have a grid with four columns. a single row have four input text boxes (one for each column ) for data entry. the first time the grid load it should have a single row with four inputs, with the cursor focused to first input. when user enter some data and press 'enter' key, the focus should move to next cell input in the same row. when you press enter in the last column input, a new row should be added to the grid and the data entered should be saved on the grid. focus should go to new row's first input. all cells should be editable and navigatable with enter key.
Can some one please give me a solution for this in angularjs/ javascript? Im using angularjs with kendo grid.
//-> Grid Start
var d2 = [
{ ConnectionReference: '001', ContractNumber: '', Amount: '', ReferenceNumber: '' },
{ ConnectionReference: '002', ContractNumber: '', Amount: '', ReferenceNumber: '' },
{ ConnectionReference: '003', ContractNumber: '', Amount: '', ReferenceNumber: '' },
{ ConnectionReference: '004', ContractNumber: '', Amount: '', ReferenceNumber: '' }];
var dataSource2 = new kendo.data.DataSource({
//data: data,
transport: {
read: function (e) {
e.success(d2);
},
update: function (e) {
e.success();
},
create: function (e) {
var item = e.d2;
item.Id = d2.length + 1;
e.success(item);
}
},
schema: {
model: {
id: "Id",
fields: {
'ConnectionReference': { editable: true, type: "string" },
'ContractNumber': { editable: true, type: "string" },
'Amount': { editable: true, type: "number" },
'ReferenceNumber': { editable: true, type: "string" }
}
}
}
});
var grid2 = $("#desgrid").kendoGrid({
dataSource: dataSource2,
scrollable: true,
navigatable: true,
toolbar: ["save", "cancel", "create"],
columns: [
{
field: "ConnectionReference",
// attributes: {
// "class": "colclass"
// "navi-text": ""
// },
// headerTemplate: 'Connection Reference',
// template: '<input ng-keydown="AA(this,$event)" type ="text" class="k-fill text-right aa" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" />',
width: "130px"
},
{
field: "ContractNumber",
// attributes: {
// "class": "colclass"
// "navi-text": ""
// },
// headerTemplate: 'Contract Number',
// template: '<input ng-keydown="AA(this,$event)" type ="text" class="k-fill text-right aa" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" />',
width: "130px"
},
{
field: "Amount",
// attributes: {
// "class": "colclass"
// "navi-text": ""
// },
// headerTemplate: 'Amount',
// template: '<input ng-keydown="AA(this,$event)" type ="text" class="k-fill text-right aa" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" />',
width: "130px"
},
{
field: "ReferenceNumber",
// attributes: {
// "class": "colclass"
// "navi-text": ""
// },
// headerTemplate: 'Reference Number',
// template: '<input ng-keydown="AA(this,$event)" type ="text" class="k-fill text-right aa" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" />',
width: "130px"
}
],
editable: {
createAt: "bottom"
},
navigatable: true
//edit: function onEdit(e) {
// var grid = this;
// var cellIndex = e.container.index();
// var nextCell = e.container.next().eq(cellIndex);
// if (nextCell) {
// e.container.find("input").on("keypress", function (e) {
// if (e.which === 13) {
// $(this).trigger("change");
// grid.closeCell();
// grid.editCell(nextCell);
// }
// });
// }
//},
}).data("kendoGrid");
grid2.tbody.on('keydown', function (e) {
if ($(e.target).closest('td').is(':last-child') && $(e.target).closest('tr').is(':last-child')) {
grid2.addRow();
}
})
// grid2.tbody.on('keydown', function (e) {
// var key = e.keyCode ? e.keyCode : e.which;
// if (key === 13) {
// var focusedElement = $(e.target);
// var nextElement = focusedElement.parent().parent().parent().next();
// var nextElement = focusedElement.next();
// if ($(e.target).closest('td').is(':last-child') && $(e.target).closest('tr').is(':last-child')) {
// if (nextElement.find('input').length > 0) {
// grid2.addRow();
// }
//}
// }
// })
$scope.submitForm = function () {
// $scope.alertMessage = new Message("0", "NIC format is invalid!");
//var fun = $scope.callback();
//var d = $scope.dgGridAddPaymentsEnter.data();
//d.splice(0, 1);
//fun($scope.params.Qty, $scope.dgGridAddPaymentsEnter.data());
}
Hello i am designing a webserver which shows me a power consumption graph from a mysql database. I am a beginner and have written a code with some help that uses ajax calls to fetch the data from the database and plot it on the highcharts. Problem is that I get all the historic values saved in my database but I want only the values of current day to be plotted on the chart. This is my js code:
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'area',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100
},
yAxis: {
title: {
text: 'POWER'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%d-%m-%Y %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y);
}
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
series: [{
name: 'Power Consumption',
data: (function () {
var data = [], i, t, d;
var request = {};
request['EndPoint'] = "arduino/charts/analog/fetch";
$.ajax({
type: "POST",
url: "../Server/fyp-processor.php",
data: JSON.stringify(request),
dataType: "json",
async: false,
success: function (result) {
if(result.Code == "1008" && (result.Data != null || result.Data != undefined)) {
for(i = 0; i < result.Data.Historic.length; i++) {
t = result.Data.Historic[i].DateTime.split(/[- :]/);
d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
data.push({
x: d,
y: parseInt(result.Data.Historic[i].Value)
});
}
}
}
});
return data;
}())
}]
});
It calls a fyp-processor php script that contains this code:
else if($postData['EndPoint'] == 'arduino/charts/analog/fetch') {
#result set
$resultSet = null;
#get all historic analog chart data
$results = $db->charts();
if(count($results) > 0) {
foreach($results as $result) {
$resultSet['Historic'][] = $result;
}
}
I would be glad if anyone could help me out to get only current DAY's data and also what changes I can do to it then to get current month and current week's data too.
I would like to show multiple series of datas in a hightcharts in a google map infowindow.
It works for one serie but I would like to had a second one.
Anybody to help me? MANY THAAANKS!
Here's my code, but it didn't work.
index.php
<script>
var dataSeries=null;
var dataRank=null;
var selectedname="";
$(document).ready(function() {
var locations =
<?php
$query->execute();
echo ("[");
while ($data = $query->fetch()) {
echo("[".$data['hot_webid'].",'".addslashes($data['hot_name'])."',".$data['hot_starrating'].",".$data['hot_latitude'].",".$data['hot_longitude']."],");
}
echo("];");
$query->closeCursor();
?>;
var iw = new google.maps.InfoWindow();
var centerMap = new google.maps.LatLng(0,0);
google.maps.event.addListener(iw,'domready',function(e) {
// Convert date into JS UTC date
for (var k=0; k<dataSeries.length; k++) {
var d=dataSeries[k][0].split(/[- :]/);
dataSeries[k][0]=Date.UTC(d[0], d[1]-1, d[2], d[3], d[4], d[5]);
}
for (var k=0; k<dataRank.length; k++) {
var d=dataRank[k][0].split(/[- :]/);
dataRank[k][0]=Date.UTC(d[0], d[1]-1, d[2], d[3], d[4], d[5]);
}
dataChart = {
chart: {
borderWidth: 2,
renderTo: document.getElementById('container'),
zoomType: 'x',
type:"spline",
lineWidth:0,
height:600,
width:500,
marginRight:40
},
legend: {
enabled: true,
align: 'right',
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderWidth: 0,
layout: 'vertical',
verticalAlign: 'top',
y: 0,
x: -140,
shadow: false,
floating : true
},
rangeSelector: {
enabled: false
},
title: {
text: selectedname
},
subtitle: {
text: 'Prices'
},
legend: {
enabled: true,
align: 'right',
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderWidth: 0,
layout: 'vertical',
verticalAlign: 'top',
y: 0,
x: -140,
shadow: false,
floating : true
},
xAxis: {
title: {
text: 'Date/Time'
}
},
yAxis: [{
title: {
text: 'Rank'
},
height: 200,
lineWidth: 2,
opposite:false
}, {
title: {
text: 'Price'
},
top: 300,
height: 200,
offset: 0,
lineWidth: 2,
opposite:false
}],
navigator: {
enabled: false,
},
credits: {
enabled: false
},
series: [{
name: 'Rank',
color: '#4572A7',
type: 'spline',
yAxis: 0,
marker: {
enabled:true,
radius:2
},
tooltip: {
valueDecimals : 0
},
data: dataRank,
}, {
name: 'Price',
color: '#89A54E',
type: 'spline',
yAxis: 1,
marker: {
enabled:true,
radius:2
},
tooltip: {
valueSuffix: '$',
valueDecimals : 0
},
data: dataSeries,
}]
};
chart = new Highcharts.StockChart(dataChart);
});
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(0.0, 0.0),
mapTypeId : google.maps.MapTypeId.ROADMAP, // Type de carte, diff�rentes valeurs possible HYBRID, ROADMAP, SATELLITE, TERRAIN
streetViewControl: false,
center: centerMap,
panControl: false,
zoomControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var inputLocation = /** #type {HTMLInputElement} */(document.getElementById('search-city'));
// Link it to the UI element.
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(inputLocation);
var autocompleteLocation = new google.maps.places.Autocomplete(inputLocation);
autocompleteLocation.bindTo('bounds', map);
/******************** LISTENER ************************/
google.maps.event.addListener(autocompleteLocation, 'place_changed', function() {
inputLocation.className = '';
var placeStart = autocompleteLocation.getPlace();
if (!placeStart.geometry) {
// Inform the user that the place was not found and return.
inputLocation.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (placeStart.geometry.viewport) {
map.fitBounds(placeStart.geometry.viewport);
} else {
map.setCenter(placeStart.geometry.location);
map.setZoom(13); // Why 13? Because it looks good.
}
var address = '';
if (placeStart.address_components) {
address = [
(placeStart.address_components[0] && placeStart.address_components[0].short_name || ''),
(placeStart.address_components[1] && placeStart.address_components[1].short_name || ''),
(placeStart.address_components[2] && placeStart.address_components[2].short_name || '')
].join(' ');
}
});
/******************** END LISTENER ************************/
var marker, i;
var markers = [];
var contentDiv = '<center><h2>Price and Rank Evolution</h2></center><div id="container" class="info-box"></div>';
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map,
title: locations[i][1]+ " (" + locations[i][2] + " stars)"
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (
function(marker, i) {
return function() {
selectedname = locations[i][1];
stopAnimation(marker);
var requestR = $.ajax({
url: "../ajax/map/get-rank.php",
type: "POST",
dataType: "json",
data: { HotelId: locations[i][0] }
});
var requestS = $.ajax({
url: "../ajax/map/get-prices.php",
type: "POST",
dataType: "json",
data: { HotelId: locations[i][0] }
});
requestR.done(
requestS.done(
function(dataS, dataR, textStatus, jqXHR) {
dataRank=dataR;
dataSeries=dataS;
iw.setContent(contentDiv);
iw.open(map, marker);
}));
requestS.fail(function(jqXHR, textStatus, errorThrown) {});
return false;
}
}
)
(marker, i)
);
}
var markerCluster = new MarkerClusterer(map, markers);
google.maps.event.addListener(iw, 'closeclick', function() {});
function stopAnimation(marker) {
setTimeout(function () {
marker.setAnimation(null);
}, 3000);
}
});
</script>
And my JSON php files
<?php
header("Content-type: application/json");
include('../../db.php');
if (isset($_POST['HotelId'])) $res_idHotel=$_POST['HotelId'];
$query = $bdd->prepare("SELECT res_date, res_price ".
"FROM exp_result ".
"WHERE res_idHotel = $res_idHotel ".
"AND res_date ".
//"BETWEEN DATE( DATE_SUB( NOW() , INTERVAL 7 DAY ) ) ".
//"AND DATE ( NOW() ) ".
"GROUP BY res_date ORDER BY res_date;");
$query->execute();
$data = $query->fetch();
if ($data) {
echo "[ ";
do {
echo "[ \"".$data['res_date']."\", ".$data['res_price']." ]";
$data = $query->fetch();
if ($data) echo ",";
} while ($data);
echo "]";
} else {
echo "[]";
}
$query->closeCursor();
?>
and
<?php
header("Content-type: application/json");
include('../../db.php');
if (isset($_POST['HotelId'])) $res_idHotel=$_POST['HotelId'];
$query = $bdd->prepare("SELECT res_date, res_rank ".
"FROM exp_result ".
"WHERE res_idHotel = $res_idHotel ".
"AND res_date ".
//"BETWEEN DATE( DATE_SUB( NOW() , INTERVAL 7 DAY ) ) ".
//"AND DATE ( NOW() ) ".
"GROUP BY res_date ORDER BY res_date;");
$query->execute();
$dataR = $query->fetch();
if ($dataR) {
echo "[ ";
do {
echo "[ \"".$dataR['res_date']."\", ".$dataR['res_rank']." ]";
$dataR = $query->fetch();
if ($dataR) echo ",";
} while ($dataR);
echo "]";
} else {
echo "[]";
}
$query->closeCursor();
?>
I have a highcharts bargraph whose values are received from json whose format is as follows:
"bargraph":
[
{
"categories": "['S', 'M', 'T', 'W', 'T', 'F']",
"series1": "[800, 1100, 80, 1800, 1600, 2000]",
"series2": "[800, 1100, 80, 1800, 1200, 800]"
}
]
How can i embed those values for my bargraph in angularJS
HTML Code:
<div id="bargraph" bargraph={{bargraph}}><\div>
Directive:
angular.module('example').directive('bargraph', function () {
element.highcharts({
xAxis: [
{
categories: [] //embed categories value here
},
series: [
{
name: 'series1',
data: [] //Embed series1 data here
},
{
name: 'series2',
data: [] //Embed series2 data here
}
]
})
})
Please provide a suitable way to embed the data from json.
Here is a directive i copied and pasted from my webapp it is how i render highcharts using a directive NOTE: not all of this directive is applicable to you and some of it is specific to what i needed but you get the idea.
lrApp.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
transclude: true,
replace: true,
link: function (scope, element, attrs) {
var chart = null;
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null,
},
colors: scope.$eval(attrs.colors) || null,
title: {
style: {
display: 'none'
}
},
xAxis: {
//categories: ['{"-7 days"|date_format}','{"-6 days"|date_format}','{"-5 days"|date_format}','{"-4 days"|date_format}', '{"-3 days"|date_format}', '{"-2 days"|date_format}', '{"-1 day"|date_format}', '{$smarty.now|date_format}'],
categories: scope.$eval(attrs.dates) || null,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1,
labels: {
y: 27
}
},
yAxis: {
title: {
text: null
},
min: 0,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
shadow: false,
lineWidth: 3
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '</b>';
}
}
};
//Update when charts data changes
scope.$watch(attrs.value, function (newVal, oldVal) {
if (!newVal.length) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var deepCopy = true;
var newSettings = {};
chartsDefaults.series = newVal;
chartsDefaults.colors = scope.$eval(attrs.colors);
chartsDefaults.xAxis.categories = scope.$eval(attrs.dates);
console.log(chartsDefaults);
chart = new Highcharts.Chart(chartsDefaults);
});
}
}
});
and this is how it used it obviously you would change "line" to bar:
<chart value="stats.sets" dates="stats.days" colors="stats.colors" type="line"></chart>