Flot refuses to display data, but parses JSON labels fine - javascript

I want to show a line chart with points being added dynamically to multiple series (i.e. show progress). y axis: shows a float with one number after the decimal point and on the x axi: time, ideally formatted to show hour:minute:second. This is live data obtained with Ajax, returned formatted as JSON.
The data returned:
[
{
"label": "s#2 ch#1 (ch un)", "data": [1421941072,24.8]
}
,
{
"label": "s#2 ch#2 (2_ch2)", "data": [1421941072,23.9]
}
,
{
"label": "s#2 ch#3 (N/A)", "data": [1421941072,23.9]
}
]
The Javascript is displaying one big point in the middle of the chart and the legends correctly, nothing else.
No JavaScript error. Valid JSON.
It's maddening.
The complete code:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/jquery.validity.js"></script>
<link href="./flotexamples.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript" src="js/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery.flot.time.js"></script>
<script type="text/javascript">
function fetchData()
{
$.ajax({
url: "/graphlist.php",
type: "GET",
dataType: "json",
success: onDataReceived
});
function onDataReceived(series)
{
data = series;
var options =
{
series:
{
lines:
{
show: true,
},
points: {
show: true
}
},
xaxis:
{
mode: "time"
},
yaxis:
{
tickDecimals: 1
}
};
$.plot("#placeholder", data, options);
}
}
// every 5 seconds
var interval = 5000;
var tid = setInterval(fetchData, interval);
</script>
Any help greatly appreciated!
TIA,
Bert

You're data isn't correctly formatted. If I'm interpreting your intention correctly, the data should probably be
[
{
"label": "s#2 ch#1 (ch un)", "data": [[1421941072,24.8]]
}
,
{
"label": "s#2 ch#2 (2_ch2)", "data": [[1421941072,23.9]]
}
,
{
"label": "s#2 ch#3 (N/A)", "data": [[1421941072,23.9]]
}
]
Note that the data property is an array of arrays.
Of course, with this construction each data series is just a single data point, but that's the only way I can interpret your question. I'm assuming that later updates will add more points to each series.
You might find this chapter on flot helpful.

Related

How to import Elasticsearch data(JSON) into Google Charts?

I try to use Elasticsearch data to create a table with Google Charts. I followed this solution: Populate Google Chart with Search Data from Elasticsearch
But I cannot see any data or graph displayed. I think it is because I don't transfer data correctly. Could anyone tell me the problem of the following code?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
google.load('visualization', {'packages':['table']});
google.setOnLoadCallback(drawTable);
function drawTable() {
var json;
$.ajax({
url: 'http://localhost:9200/people/man/_search',
type: 'POST',
data :
JSON.stringify(
{
"query" : { "match_all" : {} }
}),
dataType : 'json',
async: false,
success: function(data){
json = data;
}
})
var jdata = {};
jdata.cols = [
{
"id": "",
"label": "name",
"type": "string"
},
{
"id": "",
"label": "country",
"type":"string"
}
];
jdata.rows = [
{
"c": [
{
"v": json.hits.hits[0]._source.name
},
{
"v": json.hits.hits[0]._source.country
}
]
}
];
var data = new google.visualization.DataTable(jdata);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
</script>
</head>
<body>
<div id="table_div"> </div>
</body>
</html>
I find three problems of showing nothing in this code. No big error but good details to notice.
add header "Content-Type", "application/json". I used "xmlhttp.setRequestHeader("Content-Type", "application/json");"
'json' is defined in a function. If using json outside the function, it gives blank file back.(small error, but quite annoying if you don't notice this)
don't forget to transfer string to json with "var json = JSON.parse(json);"

Vertical stacked bar chart using SharePoint List

I have to create a stacked bar chart using the SharePoint complex list data using REST, JavaScript. The main problem here is i am not getting proper data sets.
Let me clear my scenario here: Suppose i am having a SharePoint-2013 list with 6 columns. I need a bar char based on column-1(Project Type) on x-axis, stacked by column-2(Technology) via count of different technology on y-axis. I am having 7 project type & 15 technology & want to processed around 200 rows with combination of them.
Project Java Python SharePoint .Net
A 3 5 12 1
B 4 7 6 3
C 0 9 1 0
I open with any Chat.js whether it is chart.js/google chart.js/highlight chat.js The only thing i need data to be dynamic means whenever user add more values to project column should added to x-axis automatically.
I am very new to this. Can anyone please help me to get this. need code part also. Many thanks in advance.
The code example for your reference:
<div style="width:600px;height:400px;">
<canvas id="myChart" width="600" height="400"></canvas>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script type="text/javascript">
var colors = ["#009EA0", "#A7A9AC", "#D15F27", "#BAD80A", "#E0AA0F", "#754760", "#373535"];
var listName = "CL26"; //Data List Name
var xAxisName="Title";
var yAxisName=["Java","Python","SharePoint","DotNet"];
$(document).ready(function() {
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/Web/Lists/getByTitle('"+listName+"')/items";
//execute AJAX request
$.ajax({
url: requestUri,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
var myLabels=[];
var myDataSets=[];
$.each(data.d.results, function(i, item) {
myLabels.push(item[xAxisName]);
});
for(var i=0;i<yAxisName.length;i++){
var myData=[];
$.each(data.d.results, function(j, item) {
myData.push(item[yAxisName[i]]);
});
myDataSets.push({
label:yAxisName[i],
backgroundColor:colors[i],
data:myData
});
}
buildBarChart(myLabels,myDataSets);
},
error: function () {
//alert("Failed to get details");
}
});
});
function buildBarChart(myLabels,myDataSets){
var barChartData = {
labels: myLabels,
datasets: myDataSets
};
var ctx = document.getElementById('myChart').getContext('2d');
var myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'MyProject'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
}
</script>

Highcharts renders the other graph's data too

I have one html page where there are two divs. In each div I am loading different jsp files(one.jsp and two.jsp).
home.html:
<script src="resources/js/jquery.js"></script>
<script type="text/javascript" src="resources/js/highcharts.js"></script>
<script type="text/javascript" src="resources/js/exporting.js"></script>
<script type="text/javascript" src="resources/js/export-csv.js"></script>
<script>
function loadGraphs()
{
$('#plotContainer1').load('one.jsp');
$('#plotContainer2').load('two.jsp');
}
</script>
where plotContainer1 and plotContainer2 are two divs. So that I want to load two graphs at a time.
one.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<div id="container1" style="min-width: 350px; height: 350px; margin: 0 auto"></div>
<script type="text/javascript">
var seriesArray;
var chart;
callAjax();
var graphTitle = "";
var chart;
function drawgraph1() {
Highcharts.setOptions({
colors: ['#54CBE5', '#57B442']
});
chart = $('#container1').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: graphTitle
},
xAxis: {
tickInterval: 30,
type: 'datetime',
categories: xAxisCategories
},
yAxis: {
min : 0,
title: {
text: ''
},
plotLines : [ {
value : 0,
width : 1,
color : '#808080'
} ]
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
series : seriesArray
});
};
function callAjax() {
$("#container1").empty();
seriesArray = [{
name: 'line1',
data: []
}, {
name: 'line2',
data: []
}];
xAxisCategories = [];
var params = {"param1" : value};
$.getJSON("graph1datafetcher",params, function(data) {
$.each(data, function(key, val) {
var xaxisPoints=data[key];
xAxisCategories.push(Date.parse(key));
for(var i in xaxisPoints) {
seriesArray[i].data.push(xaxisPoints[i]);
}
});
console.log(" JSON: " + JSON.stringify(data));
drawgraph1();
});
}
</script>
</body>
</html>
two.jsp almost contains the same code. Now first two.jsp loads as it contains less data compared to one.jsp. When one.jsp loads in and shows up in div, the one.jsp graph shows two.jsp data and its own data too. I am logging the data in the console, the data that is coming is fine. So, the problem is somewhere the highchart persists the first data. I have been struggling with this for past 7 hours. Can someone please answer how to resolve this?

Use server-side json with Highchart

I've searched for a few hours and looked for tons of examples, but in the end noting has worked for me.
My problem: I want to use a server-side json for a Line-Highchart. In the examples, which I've found the json comes either from a database or in an already preformated json-file.
For my use case it looks like the following: I want to visualize the value "depending" on their timestamp.
sampleData.json
[{
"timestamp": "2014-05-22T02:15:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T02:30:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T02:45:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T03:00:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T03:15:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T03:30:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T03:45:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T04:00:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T04:15:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T04:30:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T04:45:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T05:00:00+02:00",
"value": 235.0
}]
This json file is read by my getData.php
<?php
// It reads a json formatted text file and outputs it.
$json_o = file_get_contents("sampledata.json");
echo $json_o;
?>
The output looks exactly like the input, so exactly like the sampleData.json itself.
Now I use my highchart.html to create a Highchart.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- Additional files for the Highslide popup effect -->
<script type="text/javascript" src="http://www.highcharts.com/media/com_demo/highslide-full.min.js"></script>
<script type="text/javascript" src="http://www.highcharts.com/media/com_demo/highslide.config.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="http://www.highcharts.com/media/com_demo/highslide.css" />
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto">
</div><style type='text/css'></style>
<script type='text/javascript'>
$(function () {
$(document).ready(function () {
$(document).ready(function () {
function requestData() {
$.ajax({
url : 'getData.php',
datatype : 'json',
success : function (data) {
alert(data);
chart.series[0].setData(data[0]);
},
cache : false
});
}
var chart;
//Chart bits
chart = new Highcharts.Chart({
chart : {
renderTo : 'container',
type : 'line',
events : {
load : requestData
}
},
title: {
text: 'Line Chart'
},
xAxis: {
type: 'datetime',
minRange: 1 * 24 * 3600000 // one day
},
yAxis : {
title : {
text : 'Value'
}
},
legend: {
enabled: true
},
series : [{
name : 'Random data',
data : [0]
}
]
});
});
});
});
</script>
</head>
<body></body>
</html>
I've also put all of it in a JsFiddle (unfortunately with a "XMLHttpRequest cannot load"-Error) but maybe it is useful: http://jsfiddle.net/ft8hc/1/
Now we come to my actual questions:
Until now I get no data into my Chart. Although it is created, but there is no data loaded. The json itself is loaded - alert(data) shows me the sampleData.json.
Although I've looked through existing examples, I could not figured out, how to define the attributes, which should be used to draw the line and the axes. For me timestamp and value should be used.
Additionally I am not sure, if the json Format is the right one that can be used by Highchart. Is it okay like this or do I have to parse it differently?
Would be absolutely awesome if someone could help me. I've tried it for hours without success :-(
This is because you have no data specified in your chart definition.
See:
series : [{
name : 'Random data',
data : [0]
}]
Upon getting the JSON data, you must PUSH that data into this Series.data and generate the chart thereafter.
You can refer to this solution : https://stackoverflow.com/a/8169187/3660930
Your json should
- use values x/y instead of your custom names
- date should be timestamp (time in miliseconds) [number type]
- value should be number

How to add Dynamics Ticks through JSON in Flot?

I want to change the X-Axis values from default to Dynamic Ticks which is passed from JSON.
Through my last post How to plot time values in Flot Graph, I found out that it is possible through Categories.js
I added the JS and modified My JSON in the format below matching to the format given in the Example.
[{"data":[["Over Time",5202]],"label":"Over Time"},{"data":[["Shift Start",19620]],"label":"Shift Start"},{"data":[["Maintenance break",82920]],"label":"Maintenance break"},{"data":[["Lunch break",240]],"label":"Lunch break"},{"data":[["BreakDown",75720]],"label":"BreakDown"},{"data":[["Break",3060]],"label":"Break"},{"data":[["Tea break",72840]],"label":"Tea break"}]
and my JS code as
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$.getJSON('ReasonByTime.txt', function(json) {
$.plot($("#placeholder"),json, {bars: { show: true, barWidth:0.2}, xaxis: { mode: "categories" }});
});
});
When i run this code, x-axis is not displaying any values, the default values also not getting displayed. My result graph is look like this.
I tested The sample example given in code.google.com/p/flot/ but the tickes/categories is not working. I get the Output for the example like this.
Flot is now hosted out of github: https://github.com/flot/flot
If you grab jquery.flot.js and jquery.flot.categories.js from there and run your code, it will work. What does NOT work is jquery.flot.js version 0.7 combined with the latest categories plugin from github.
I ran it with this code and it displayed correctly:
var data = [{
"data": [["Over Time", 5202]]},
{
"data": [["Shift Start", 19620]]},
{
"data": [["Maintenance break", 82920]]},
{
"data": [["Lunch break", 240]]},
{
"data": [["BreakDown", 75720]]},
{
"data": [["Break", 3060]]},
{
"data": [["Tea break", 72840]]}];
$.plot($("#placeholder"), data, {
bars: {
show: true,
barWidth: 0.2
},
xaxis: {
mode: "categories"
}
});​
Here is a working version of it: http://jsfiddle.net/ryleyb/CQ3YS/

Categories

Resources