Graphic counter correction - javascript

I have a chart and my system that I need it to report the exact value of the search results.
Due to many data, the results come out so 1.1K.
In the place that 1.1K wanted it shows the exact value that would be 1057.
Here is the graph function in JS:
function Post(url, param, title, totalText) {
totalText = totalText || "Total";
$.ajax({
method: "POST",
url: "/Graficos/" + url,
data: param,
beforeSend: function () {
showLoader();
},
success: function (data) {
ChartConstructor(title, JSON.stringify(data), totalText);
},
complete: function () {
hideLoader();
}
});
}
function ChartConstructor(title, dados, totalText) {
window.google.charts.load('current', { 'packages': ['bar'] });
window.google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var table = JSON.parse(dados);
var rows = "";
var array = [["", "Total"]];
for (var i = 0; i < table.length; i++) {
array.push([table[i].Title, table[i].Count]);
}
var data = new google.visualization.arrayToDataTable(array);
var options = {
width: '100%',
height: 400,
chart: {
title: title,
},
bar: { groupWidth: '95%' },
bars: 'horizontal',
series: {
0: { axis: 'distance' },
}
};
var chart = new google.charts.Bar(document.getElementById("chart-content"));
chart.draw(data, options);
$("#chart-type").val("");
}
}

According to the documentation, you can set the format of hAxis or vAxis to 'none' to display the full number.
Example:
var options = {
width: '100%',
height: 400,
chart: {
title: title,
},
bar: { groupWidth: '95%' },
bars: 'horizontal',
series: {
0: { axis: 'distance' },
},
vAxis: {
format: 'none'
}
};

Related

How to poll data using Ajax request?

I am trying to poll my data in HighCharts. The graph in this link is what I am trying to achieve. I am using Ajax request to retrieve my data. Here is my code:
setInterval(RefreshGraph, 3000);
...
...
function RefreshGraph() {
var options = {
chart: {
type: 'spline'
},
title: {
text: 'Text'
},
xAxis: {
title: {
text: 'TIMEFRAME'
},
categories: ['-4m', '-3m', '-2m', '-1m', 'Now']
},
yAxis: {
title: {
text: 'NUMBER'
},
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 2
}
}
},
series: [{}]
};
Highcharts.ajax({
url: "/Home/GetData",
success: function (data) {
var formattedData = FormatData(data);
//Graph 1
options.series[0] = formattedData[0];
//Graph 2
options.series[1] = formattedData[1];
Highcharts.chart("container", options);
}
});
}
However, the entire graph gets redrawn with my above code. How can I enable live polling for the above code?
You create a chart every time data is received. You need to create a chart and then update it. Example:
const options = {...};
const chart = Highcharts.chart("container", options);
function RefreshGraph() {
Highcharts.ajax({
url: "/Home/GetData",
success: function(data) {
var formattedData = FormatData(data);
chart.update({
series: [formattedData[0], formattedData[1]]
});
}
});
}
setInterval(RefreshGraph, 3000);
Live demo: http://jsfiddle.net/BlackLabel/6d5stjab/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update

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]]

reading data from CSV and show continuous graph

I am trying to plot a chart which will read a data from csv file which is appending on every minute with latest data as per below format.
The chart will continue reading data from csv file and show the graph on every second wise. Can you please help me on this? I want to show the exact time which are coming from file should be show on graph.
CSV format..
time,count
18:01:00,3
18:01:01,4
....
$(document).ready(function () {
var csv = [],
x;
Highcharts.setOptions({
global: {
useUTC: false
}
});
var data = 'time,count\n18:01:00,3\n18:01:01,4';
//$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
if(lineNo > 0) {
var items = line.split(',');
useUTC: false;
x = items[0].split(':');
csv.push([Date.UTC(2015,1,1,x[0],x[1],x[2]), parseFloat(items[1])]);
}
});
console.log(csv);
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
useUTC: false,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var l = series.data.length - 1,
lastX = series.data[l].x;
$.get('data.csv', function(data) {
var lines = data.split('\n'),
len = lines.length,
items = lines[len - 1].split(','),
x = items[0].split(':'),
y = parseFloat(items[1]);
useUTC: false;
x = Date.UTC(2015,1,1,x[0],x[1],x[2]);
if(x !== lastX) {
series.addPoint([x, y], true, true);
}
});
}, 1000); //refresh each 1 second
}
}
},
title: {
text: 'TPS Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 3,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Count',
data: csv
}]
});
//});
});
div {
min-width: 50px;
height: 200px;
margin: 0 auto;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style=""></div>
Note In the snippet I was replace the ajax function $.get with hardcoded data so it will show the result but the question is about the ajax way.

Highcharts bar chart wont animate

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

highcharts dynamically adding series with addSeries

I'm working on creating a dynamically created chart that will add a series if there isn't one and if there is one add a point. I'm getting an Uncaught TypeError: Cannot call method 'addSeries' of undefined. I've looked around and I can't find why it says that method is undefined.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
$(document).ready(function () {
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
events: {
load: requestData
}
},
title: {
text: 'Survey Chart'
},
xAxis: {
categories: [],
title: {
text: 'Question Number'
}
},
yAxis: {
title: {
text: 'Total Answered'
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true
},
series: []
});
with the document ready function taking up the entire script i have the following functions
function requestData() {
ajaxCall(chartCreate, createSeries, "services/Survey.svc/DoWork", "{}");
chart1.redraw();
};
function chartCreate(point) {
var temp;
temp = $.parseJSON(point.d);
$.each(temp, function (key, p) {
var seriesObj;
seriesObj = seriesExists(p.mcAnswer);
if (seriesObj.status == false) {
chart1.addSeries({name: '' + p.mcAnswer + '', data: [] });
chart1.series[seriesObj.count].addPoint(p.total, false);
} else {
chart1.series[seriesObj.count].addPoint(p.total, false);
}
});
};
//loops through all the series to see if the series exists.
//if true returns index and true if not just returns false
function seriesExists(name) {
var ct = 0;
//var len = chart1.series.length;
var len = 0;
if (len > 0) {
$.each(chart1.series, function (count, curSeries) {
if (curSeries.name == name) {
return { 'count': count, 'status': true };
}
ct = count;
});
}
return { 'count': ct, 'status': false };
}; function createSeries() {
alert("error");
};
//$.ajaxCall({successFun: function, errorFun: function, source: "", data: {}});
function ajaxCall(myFunSuccess, myFunError, url, data) {
//chart1 = chartTemp;
$.ajax({
type: "POST",
async: false,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: myFunSuccess,
error: myFunError
});
//return chart1;
};
I'm able to use the ajax function call fine it's when I get to my chartCreate where I run into the problem.
The problem is that you're trying to add the serie before chart1 get your chart reference. That's why chart1 doens't have addSeries method.
You can see this issue here.
To fix it you can set manually the chart reference to chart1 before call requestData.
Like the following.
load: function() {
chart1 = this; // `this` is the reference to the chart
requestData();
}

Categories

Resources