Problems with tickInterval in jqPlot - javascript

I'm new to jqplot but am using it on a very important project. I am trying to have the x-axis have one 'tick' for each day -- as of now, there are multiple ones. Here is a screenshot:
Here is the code (in which I also added a min and max as this post referred):
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
async: false,
url: url,
type: "GET",
dataType:"json",
data: {metricName: ""},
success: function(data) {
ret = data;
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
return ret;
};
//var jsonurl = "reports/reportData.json";
var jsonurl = "tenant/metrics/get.json";
var today = new Date();
var plot2 = $.jqplot('chart2', jsonurl,{
title: "",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {unusedOptionalUrl: jsonurl},
axes: {
xaxis: {
'numberTicks' : 7,
min: '2012-10-05',
max: today,
renderer:$.jqplot.DateAxisRenderer,
rendererOptions:{tickRenderer:$.jqplot.CanvasAxisTickRenderer},
tickInterval: '1 day',
tickOptions:{formatString:'%Y-%#m-%#d'
}
//rendererOptions: {sdaTickInterval: [1, 'month']}
},
yaxis: {
label: "MB",
tickOptions:{formatString:'%d '},
// Comment the next line out to allow negative values (and therefore rounded ones)
min: 0
}
}
});
});
Even if I manually set the clicks like this:
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
async: false,
url: url,
type: "GET",
dataType:"json",
data: {metricName: ""},
success: function(data) {
ret = data;
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
return ret;
};
//var jsonurl = "reports/reportData.json";
var jsonurl = "tenant/metrics/get.json";
var today = new Date();
var plot2 = $.jqplot('chart2', jsonurl,{
title: "",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {unusedOptionalUrl: jsonurl},
axes: {
xaxis: {
'numberTicks' : 7,
min: '2012-10-05',
max: today,
renderer:$.jqplot.DateAxisRenderer,
rendererOptions:{tickRenderer:$.jqplot.CanvasAxisTickRenderer},
ticks: ['2012-10-05','2012-10-06','2012-10-07','2012-10-08', today],
tickOptions:{formatString:'%Y-%#m-%#d'
}
//rendererOptions: {sdaTickInterval: [1, 'month']}
},
yaxis: {
label: "MB",
tickOptions:{formatString:'%d '},
// Comment the next line out to allow negative values (and therefore rounded ones)
min: 0
}
}
});
});
The marks do not match up to their correct dates. Here is a screenshot:
Is there a sane way to do this? I want each x-axis tick to be only one date, and the data entry mark to be on that tick's axis.
This is driving me crazy! Please help!
Also, here is my json
[[["2012-10-05 10:57:16AM", 0],["2012-10-05 11:02:14AM", 2449],["2012-10-08 08:17:47AM", 9639],["2012-10-08 08:17:53AM", 224768],["2012-10-09 07:43:19AM", 9640],["2012-10-09 07:44:01AM", 224769]]]

Your format string isn't correct as it doesn't include the timestamp; try changing it to the following:
tickOptions:{formatString:'%y-%#m-%#d%n%#I:%#M:%#S%p}
Alternatively, if you don't need the timestamp, leave your format string as is and remove the timestamp from the JSON.
EDIT
If the above format string doesn't work, try manipulating the values to match using the values as below:
// Year
%Y 2008
%y 08
// Month
%m 09
%#m 9
%B September
%b Sep
// Day
%d 05
%#d 5
%e 5
%A Sunday
%a Sun
%w 0, 0 = Sunday, 6 = Saturday
%o th, The ordinal suffix string following the day of the month
// Hour
%H 23
%#H 3
%I 11
%#I 3
%p PM, AM or PM
// Minute
%M 09
%#M 9
// Second
%S 02
%#S 2
%s 1206567625723, Unix timestamp, seconds past 1970-01-01 00:00:00
// Millisecond
%N 008
%#N 8
I hope this helps!

Related

Highcharts: create multiple series grouped my month and year using JSON data

I am trying to create a line, spline chart using JSON data. I want multiple series but I am confused on how to do that. Right now I am able to create the multiple series when the date is in 2019-07-06 format. I also have a JSON that has a column for the month and a column for the year Please help on how I can fix this. Right now I only have the code for group by day.
JSON Data:
[
{ "month": 6,
"year": 2019,
"starts": 21278998,
"completes": 9309458
},
{ "month": 7,
"year": 2019,
"starts": 38850115,
"completes": 17790105
}
]
I used the solution for the date format 2019-07-06 provided in this fiddle: https://jsfiddle.net/BlackLabel/tjLvh89b/
Please help with how I can create a chart for the Month, Year on the x-Axis.
You can achieve it simply by creating a Date object using different parameters.
Instead of the string date parameter new Date('2019-07-07') use year and month as separate parameters like that: new Date(2019, 7).
Code:
var json = [{
month: 6,
year: 2019,
starts: 21278998,
completes: 9309458
}, {
month: 7,
year: 2019,
starts: 38850115,
completes: 17790105
}];
var series1 = {
name: 'starts',
data: []
},
series2 = {
name: 'completes',
data: []
};
json.forEach(elem => {
series1.data.push({
x: +new Date(elem.year, elem.month),
y: elem.starts
});
series2.data.push({
x: +new Date(elem.year, elem.month),
y: elem.completes
});
});
Highcharts.chart('container', {
chart: {
type: 'spline'
},
xAxis: {
type: 'datetime'
},
series: [
series1,
series2
]
});
Demo:
https://jsfiddle.net/BlackLabel/xtefuLsp/1/
Date object reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

CanvasJS Line Chart with Date Selector & Range Selector Using Api

So, i have a similar code as here: https://jsfiddle.net/canvasjs/zxrkh502/
But i need put data from ajax/json instead of randomData function. How can i do it?
var dps = [];
var chart = new CanvasJS.Chart("chartContainer",
{
title: {
text: "Chart with Date Selector"
},
data: [
{
type: "line",
dataPoints: randomData(new Date(2017, 0, 1), 400)
}
]
});
chart.render();
etc...
Thank You!
make the ajax call first, build the data array,
then continue with the rest of the code.
see following snippet...
$.ajax({
url: 'http://get-data-url',
type: 'GET',
headers: {accept: 'application/json;odata=verbose;'}})
.done(drawChart)
.fail(function (jqXHR, status, errorThrown) {
console.log('problem loading data: ' + errorThrown);
});
function drawChart(data) {
var dps = [];
$.each(data, function (rowIndex, row) {
dps.push({
x: row.xValue,
y: row.yValue
});
});
var chart = new CanvasJS.Chart("chartContainer",
{
title: {
text: "Chart with Date Selector"
},
data: [
{
type: "line",
dataPoints: dps
}
]
});
chart.render();
var axisXMin = chart.axisX[0].get("minimum");
var axisXMax = chart.axisX[0].get("maximum");
$("#fromDate").val(CanvasJS.formatDate(axisXMin, "DD MMM YYYY"));
$("#toDate").val(CanvasJS.formatDate(axisXMax, "DD MMM YYYY"));
$("#fromDate").datepicker({dateFormat: "d M yy"});
$("#toDate").datepicker({dateFormat: "d M yy"});
$("#date-selector").change( function() {
var minValue = $( "#fromDate" ).val();
var maxValue = $ ( "#toDate" ).val();
if(new Date(minValue).getTime() < new Date(maxValue).getTime()){
chart.axisX[0].set("minimum", new Date(minValue));
chart.axisX[0].set("maximum", new Date(maxValue));
}
});
$(".period").click( function() {
var period = this.id;
var minValue;
minValue = new Date(axisXMax);
switch(period){
case "1m":
minValue.setMonth(minValue.getMonth() - 1);
break;
case "3m":
minValue.setMonth(minValue.getMonth() - 3);
break;
case "6m":
minValue.setMonth(minValue.getMonth() - 6);
break;
case "1y":
minValue.setYear(minValue.getFullYear() - 1);
break;
default:
minValue = axisXMin;
}
chart.axisX[0].set("minimum", new Date(minValue));
chart.axisX[0].set("maximum", new Date(axisXMax));
});
}

JSONp Datetime Javascript query fails on data.sparkfun iot

been trying to select data from data.sparkfun based on when its posted. I want to display weather data from the currenttime and a day back.
The stream is at: LINK
I am no coder, just hacking my way through here.
One json line is like this:
[{
"humidity": "37.8919",
"hectopascals": "1017.7725",
"rainin": "0.0000",
"tempc": "21.3162",
"winddir": "-1",
"windspeedkmh": "0.0000",
"windgustkmh_10m": "0.0000",
"timestamp": "2017-02-25T15:11:08.581Z"
}]
The code I use is at: https://www.hanscees.com/photon/charts-data-sparkfun.html
function drawChart2() {
var public_key = 'yA0EjKV3owhKNx1NlN3w';
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {
'gt': {
'timestamp': 'now - 2d'
}
},
dataType: 'jsonp',
}).done(function(results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'TempC');
data.addColumn('number', 'Humidity');
$.each(results, function(i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.tempc),
parseFloat(row.humidity)
]);
}); // each row
// see https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#dual-y-charts
var materialOptions = {
chart: {
title: 'TempC, Humidity outside'
},
width: 550,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {
axis: 'TempC'
},
1: {
axis: 'Humid'
}
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Pressure: {
label: 'TempC (Celsius)'
},
Humid: {
label: 'Humidity'
}
}
}
};
var materialChart = new google.charts.Line(ChartDivTemp);
materialChart.draw(data, materialOptions);
}); // results
} // jsondata
but the diagrams are either displaying all data in the json file (which makes it extremely slow), or when I use:
data: {page: 1},
it shows about 4 hours of data.
How can help to format the query correctly? This line:
data: {
'gt': {
'timestamp': 'now - 2d'
}
}
I did a post request thru Postman and it worked:
https://data.sparkfun.com/output/yA0EjKV3owhKNx1NlN3w.json?lt[timestamp]=now%20-2day
data: {
'lt': {
'timestamp': 'now - 2day'
}
}
So you code should work by adding 2day and changing gt to lt
This code does what I wanted:
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {'gt': {'timestamp': 'now - 2day'}},
dataType: 'jsonp',
}).done(function (results) {

How to move Google Charts colour settings from file to another

So I am working on a project where the code already exists.
On 2 files as below, I need to remove the colour settings from the first file to the second file somehow in the IF statement.
The reason is the first file will be populated/injected with info from the backend but in order to do so I have to remove from the datasets propeties (label, fillColor, strokeColor, pointColor, pointStrokeColor, pointHighlightFill and pointHighlightStroke) array in file 1 to file 2 so to seperate styles from actual data that will be injected
I have tried simply adding the datasets section to the second file but just doesn't show anything - can it be added to the Chart.types.Line.extend object or the AJAX section somehow?
Many thanks in advance
File 1: (Will have data injected to it):
{
"labels":[
"1 Feb",
"8 Feb",
"15 Feb",
"22 Feb",
"29 Feb",
"7 Mar",
"14 Mar",
"21 Mar",
"28 Mar",
"4 Apr",
"11 Apr",
"18 Apr",
"25 Apr"
],
"datasets":[
{
"label":"Tenders",
"fillColor":"rgba(253,0,20,0.2)",
"strokeColor":"rgba(253,0,20,1)",
"pointColor":"#fff",
"pointStrokeColor":"rgba(253,0,20,1)",
"pointHighlightFill":"#fff",
"pointHighlightStroke":"rgba(253,0,20,1)",
"data":[
77,
55,
40,
65,
59,
80,
81,
56,
55,
65,
59,
80,
75
]
}
]
}
File 2: (Where I want datasets properties to be):
if (document.getElementById("chart_div_won")) {
Chart.types.Line.extend({
name: "LineAlt",
initialize: function(data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
var xLabels = this.scale.xLabels;
var xLabelsLength = xLabels.length;
xLabels.forEach(function(label, i) {
if (i % 4 != 0 || i <= 1 || i == xLabelsLength - 1)
xLabels[i] = '';
})
}
});
var form_data = {};
$.ajax({
type: "GET",
url: "../../../sample_data/chart1.json",
data: form_data,
success: function(response) {
var ctx = document.getElementById("chart_div_won").getContext("2d");
var options = {
responsive: true,
maintainAspectRatio: true,
pointDotRadius: 5,
showXLabels: 5,
};
var myLineChart = new Chart(ctx).LineAlt(response, options);
},
error: function() {
$('div#chart-container').html('<div class="notification-body"><p class="notification-heading">Loading error...</p><p class="notification-description">Unfortunatley for some reason visual data failed to load.</p></div>');
},
dataType: "json",
contentType: "application/json; charset=utf-8",
});
}
So I this is as far as I have got:
if (document.getElementById("chart_div_won")) {
Chart.types.Line.extend({
name: "LineAlt",
initialize: function(data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
var xLabels = this.scale.xLabels;
var xLabelsLength = xLabels.length;
xLabels.forEach(function(label, i) {
if (i % 4 != 0 || i <= 1 || i == xLabelsLength - 1)
xLabels[i] = '';
})
}
});
var datasets = [{
"label":"Tenders",
"fillColor":"rgba(253,0,20,0.2)",
"strokeColor":"rgba(253,0,20,1)",
"pointColor":"#fff",
"pointStrokeColor":"rgba(253,0,20,1)",
"pointHighlightFill":"#fff",
"pointHighlightStroke":"rgba(253,0,20,1)"}
];
var form_data = {};
$.ajax({
type: "GET",
url: "../../../sample_data/chart1.json",
data: form_data.push(datasets),
success: function(response) {
var ctx = document.getElementById("chart_div_won").getContext("2d");
var options = {
responsive: true,
maintainAspectRatio: true,
pointDotRadius: 5,
showXLabels: 5,
};
var myLineChart = new Chart(ctx).LineAlt(response, options);
},
error: function() {
$('div#chart-container').html('<div class="notification-body"><p class="notification-heading">Loading error...</p><p class="notification-description">Unfortunatley for some reason visual data failed to load.</p></div>');
},
data: form_data.push(datasets),
dataType: "json",
contentType: "application/json; charset=utf-8",
});
}
I am trying to add an array of datasets, then add that to the array in the first file, in the datasets array. No luck but I think my code in syntactically wrong in this answer above
For anyone with this or a similar problem. It was easy in the end. All I had to do was add each property on at the end of the array.
Code
myLineChart.datasets[0].fillColor = "rgba(253,0,20,0.2)";
And so on

Flot chart displaying data from data that aren't even in JSON

I have the following
<div id="chart"></div>
<script src="js/flot/jquery.flot.js"></script>
<script src="js/flot/jquery.flot.tooltip.min.js"></script>
<script src="js/flot/jquery.flot.resize.js"></script>
var sessions = [
[1418706000000, 14813],
[1418792400000, 39580],
[1418878800000, 51193],
[1418965200000, 66700],
[1419051600000, 108737],
[1419138000000, 101081],
[1419224400000, 94449],
[1419310800000, 109039],
[1419397200000, 92329],
[1419483600000, 68942],
[1419570000000, 75391],
[1419656400000, 120016],
[1419742800000, 132495],
[1419829200000, 103469],
[1419915600000, 88940],
[1420002000000, 59938],
[1420088400000, 72359],
[1420174800000, 74663]
];
var users = [
[1418706000000, 2632],
[1418792400000, 9588],
[1418878800000, 9273],
[1418965200000, 10839],
[1419051600000, 14948],
[1419138000000, 11226],
[1419224400000, 13394],
[1419310800000, 10493],
[1419397200000, 8482],
[1419483600000, 2375],
[1419570000000, 5783],
[1419656400000, 10068],
[1419742800000, 8288],
[1419829200000, 5423],
[1419915600000, 4866],
[1420002000000, 1862],
[1420088400000, 5560],
[1420174800000, 1257]
];
function doPlot(position) {
$.plot($("#chart"), [{
data: sessions,
label: "Sessions"
}, {
data: revenue,
label: "Revenue",
yaxis: 2
}], {
xaxes: [{
mode: 'time'
}],
yaxes: [{
min: 0
}, {
alignTicksWithAxis: position == "right" ? 1 : null,
position: position
}],
legend: {
position: 'sw'
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%s for %x was %y",
xDateFormat: "%y-%0m-%0d",
onHover: function (flotItem, $tooltipEl) {
}
}
});
}
doPlot("right");
Thhis displays figures for both sessions and users on dates that there isn't even data for. The last date that there is data for is Dec 27th. Yet, this line graph shows data for up until Jan 2nd.
Here is a working example here
Any ideas?
According to your last data entry in each array element time = 1420174800000, so:
var date = new Date(1420174800000);
// output "Fri, 02 Jan 2015 05:00:00 GMT"
console.log(date.toGMTString());
I converted your data to dates:
date = new Date(sessions[i][0])
It contains dates between Dec 16 2014 and Jan 02 2015. You can see it in this fiddle.
When you fill your arrays, you should convert your dates to numbers simply with:
sessions[i] = [Number(date), value];
I'm not sure how you meant Date('D, M j'), I assume it's a string like "Date(month,day,year)". An example of converting this kinf of json to plottable data: in this other fiddle.
Actually, I reversed the day and month, but you get the idea. :)

Categories