We want to plot live data in this site https://www.highcharts.com/demo/live-data is it possible to plot it with Highcharter library in R language if not is there any another solution to do that with R language?
Here is JavaScript code:
var defaultData = 'https://demo-live-data.highcharts.com/time-data.csv';
var urlInput = document.getElementById('fetchURL');
var pollingCheckbox = document.getElementById('enablePolling');
var pollingInput = document.getElementById('pollingTime');
function createChart() {
Highcharts.chart('container', {
chart: {
type: 'spline'
},
title: {
text: 'Live Data'
},
accessibility: {
announceNewData: {
enabled: true,
minAnnounceInterval: 15000,
announcementFormatter: function (allSeries, newSeries, newPoint) {
if (newPoint) {
return 'New point added. Value: ' + newPoint.y;
}
return false;
}
}
},
data: {
csvURL: urlInput.value,
enablePolling: pollingCheckbox.checked === true,
dataRefreshRate: parseInt(pollingInput.value, 10)
}
});
if (pollingInput.value < 1 || !pollingInput.value) {
pollingInput.value = 1;
}
}
urlInput.value = defaultData;
// We recreate instead of using chart update to make sure the loaded CSV
// and such is completely gone.
pollingCheckbox.onchange = urlInput.onchange = pollingInput.onchange = createChart;
// Create the chart
createChart();
I'd like to plot some charts using Chart.js.
I have a script that gets two arrays from a database in JSON format.
The two arrays are:
-An array of Temperature (float)
-An array of Time (Obtained by the Database at the moment in which a temperature enters it by means of the function Current_Timestamp ())
I'd like to be able to graph the temperatures depending on the date with Chart.js
$(document).ready(function(){
$.ajax({
url : "http://localhost/js/data.php",
type: "GET",
success : function(data) {
console.log(data);
var datos = {
VectorTemp : [],
VectorFecha : []
}
var len = data.length;
for (var i = 0; i<len;i++){
if (data[i].chipID == 1){
datos.VectorTemp.push(data[i].temp);
datos.VectorFecha.push(data[i].fecha);
}
}
console.log(datos);
var ctx = $("#line-chartcanvas");
var data = {
labels: [],
datasets: [
{
x: datos.VectorFecha[1],
y: datos.VectorTemp[1]
}
]
};
var options = {
responsive: true,
title: {
display: true,
text: "Chart.js Time Scale"
},
}
var chart = new Chart (ctx, {
type: "line",
data : data,
options: options
});
},
error: function(data) {
console.log(data);
},
});
});
I am trying to make a schedule of school classes, I have integrated "drag and drop" and the events are saved in the database but these are shown only during the week to which the date indicated to the event belongs. I would like that even if the current date changes to the following week, the events would still be visible and would depend on the day of the week and not on the full date.
To get the events I use the following line:
events: "../ajax/fullcalendar/response.php?view=1",
But in this question I saw an issue similar to what I want to do, but there they use a POST request as below
$.post( "getevents2.php",
{'getEvents': 1},
function(data) {
var array = JSON.parse(data);
for(i = 0; i < array.length; i++) {
$('#calendar').fullCalendar( 'renderEvent', {
title: 'Sometitle',
start: days[array[i]['day']]+'T'+array[i]['start_time'], // here we are setting needed date from array 'days' by day's name which we got from database
end: days[array[i]['day']]+'T'+array[i]['end_time'] // here's the same
} );
}
}
);
I got confused when trying to combine both codes, because the console tells me an error: "Unexpected end of JSON entry in JSON.parse (), I also saw that the person also added an array of Days to not use the full date, so When I combine my code with the other mentioned question, my code has been as follows:
//Custom
//De momento esta funcion no se usa, asi que, sigue usando fecha completa en lugar de solo 7 dias, asi que en teoria, los eventos desapareceran cuando avance el tiempo
Date.prototype.getDaysOfCurrentWeek = function(start)
{
// Array of all days of week
var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Calculates date of first day of current week
start = start || 0;
var today = new Date(this.setHours(0, 0, 0, 0));
var day = today.getDay() - start;
var date = today.getDate() - day;
// Then we are calculating all dates of current week and then reformat them into ISOO
var daysOfWeek = new Object();
for(i = 0; i < 8; i++) {
tmp = new Date(today.setDate(date+i));
daysOfWeek[days[i]] = tmp.getFullYear()+'-'+(tmp.getMonth()+1)+'-'+tmp.getDate();
}
return daysOfWeek;
}
//Ends Custom
var days = new Date().getDaysOfCurrentWeek(); // gets array like ('nameOfDay' => 0000-00-00)
$(document).ready(function(){
var currentMousePos = {
x: -1,
y: -1
};
jQuery(document).on("mousemove", function (event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events .external-event').each(function() {
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).text()), // use the element's text as the event title
color: $.trim($(this).data("color")),
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
////////////////
var calendar = $('#calendar').fullCalendar({
header:{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaWeek', //agendaWeek
editable: true,
selectable: true,
allDaySlot: false,
//Custom
// allDaySlot: false, //repetido
hiddenDays: [0], //Ocultar Domingo
columnFormat: 'dddd',
minTime: '07:00:00',
maxTime: '22:00:00',
slotDuration: "00:50:00", //Cada 54 minutos
slotLabelInterval: 50,
//slotMinutes: 54,
slotLabelFormat: 'h(:mm)a',
header: true, //lo cambie a false para esconderlo y cuando lo devolvi a true ya no aparecio el encabezado
droppable: true,
//Ends Custom
events: "../ajax/fullcalendar/response.php?view=1", //De las lineas 87 a 101, no funciono, descomentar 102
eventClick: function(event, jsEvent, view) {
endtime = $.fullCalendar.moment(event.end).format('h:mm');
starttime = $.fullCalendar.moment(event.start).format('dddd, MMMM Do YYYY, h:mm');
var mywhen = starttime + ' - ' + endtime;
$('#modalTitle').html(event.title);
$('#modalWhen').text(mywhen);
$('#eventID').val(event.id);
$('#calendarModal').modal();
},
//header and other values
select: function(start, end, jsEvent) {
endtime = $.fullCalendar.moment(end).format('h:mm');
starttime = $.fullCalendar.moment(start).format('dddd, MMMM Do YYYY, h:mm');
var mywhen = starttime + ' - ' + endtime;
start = moment(start).format();
end = moment(end).format();
$('#createEventModal #startTime').val(start);
$('#createEventModal #endTime').val(end);
$('#createEventModal #when').text(mywhen);
$('#createEventModal').modal('toggle');
},
//custom
eventReceive: function(event){
var title = event.title;
var color = event.color;
$.ajax({
url: '../ajax/fullcalendar/response.php',
data: 'action=add&title='+title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&color='+color,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
$('#calendar').fullCalendar('updateEvent',event);
console.log(event);
},
//custom
eventDrop: function(event, delta){
$.ajax({
url: '../ajax/fullcalendar/response.php',
data: 'action=update&title='+event.title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&id='+event.id ,
type: "POST",
success: function(json) {
//alert(json);
}
});
},
eventResize: function(event) {
$.ajax({
url: '../ajax/fullcalendar/response.php',
data: 'action=update&title='+event.title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&id='+event.id,
type: "POST",
success: function(json) {
//alert(json);
}
});
},
//custom
eventDragStop: function (event, jsEvent, ui, view) {
if (isElemOverDiv()) {
var eventID = $('#eventID').val();
var con = confirm('¿Estas seguro de eliminar este evento permanentemente?');
if(con == true) {
$.ajax({
url: '../ajax/fullcalendar/response.php',
data: 'action=delete&id='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
console.log(response);
// if(response.status == 'success'){
//$('#calendar').fullCalendar('removeEvents');
//$("#calendar").fullCalendar('removeEvents',+eventID);
// $("#calendar").fullCalendar('removeEvents',+response.idEvent);
//getFreshEvents();
if(response == 1)
//$("#calendar").fullCalendar('removeEvents',eventID);
$("#calendar").fullCalendar('removeEvents',event.id);
else
return false;
$('#calendar').fullCalendar( 'refetchEvents' );
// }
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
}
}
//custom
});
$('#submitButton').on('click', function(e){
// We don't want this to act as a link so cancel the link action
e.preventDefault();
doSubmit();
});
$('#deleteButton').on('click', function(e){
// We don't want this to act as a link so cancel the link action
e.preventDefault();
doDelete();
});
function doDelete(){
$("#calendarModal").modal('hide');
var eventID = $('#eventID').val();
$.ajax({
url: '../ajax/fullcalendar/response.php',
data: 'action=delete&id='+eventID,
type: "POST",
success: function(json) {
if(json == 1)
$("#calendar").fullCalendar('removeEvents',eventID);
else
return false;
}
});
}
function doSubmit(){
$("#createEventModal").modal('hide');
var title = $('#title').val();
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
var color = $('#color').val();
$.ajax({
url: '../ajax/fullcalendar/response.php',
// data: 'action=add&title='+title+'&start_time='+startTime+'&end_time='+endTime, //start='+startTime+'&end='+endTime, //Si no regreso a como estaba devuelve 1970
data: 'action=add&title='+title+'&start='+startTime+'&end='+endTime+'&color='+color, //Si no regreso a como estaba devuelve 1970
type: "POST",
success: function(json) {
$("#calendar").fullCalendar('renderEvent',
{
id: json.id,
title: title,
start: startTime,
end: endTime,
color: color,
//start: days[array[i]['day']]+'T'+array[i]['start_time'], // here we are setting needed date from array 'days' by day's name which we got from database
//end: days[array[i]['day']]+'T'+array[i]['end_time'] // here's the same
},
true);
//alert(json);
}
});
}
function getFreshEvents(){
$.ajax({
url: '../ajax/fullcalendar/response.php',
type: 'POST', // Send post data
data: 'view=1',
async: false,
success: function(s){
freshevents = s;
}
});
$('#calendar').fullCalendar('addEventSource', s.parse(freshevents));
}
function isElemOverDiv() {
var trashEl = jQuery('#trash');
var ofs = trashEl.offset();
var x1 = ofs.left;
var x2 = ofs.left + trashEl.outerWidth(true);
var y1 = ofs.top;
var y2 = ofs.top + trashEl.outerHeight(true);
if (currentMousePos.x >= x1 && currentMousePos.x <= x2 &&
currentMousePos.y >= y1 && currentMousePos.y <= y2) {
return true;
}
return false;
}
});
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) {
I have a rails app that fetches currency information data of the value of the sterling pound compared to the Kenyan shilling from a JSON API.
I want to use this data to plot a time-series graph of the value of the pound over a long period of time.
I'm using AJAX to populate data to a highcharts chart and my code is as follows:
<div id="currency", style="width: 220px, height:320px">
<script type="text/javascript">
$(document).ready(function(){
localhost = {}; //global namespace variable
localhost.currenctHTML = ""; //currency HTML built here
localhost.currencyValue = []; //array of percentage changes
localhost.currencyDate = []; //array of currency names
localhost.chart1 = {yAxisMin : null, yAxisMax : null};//obj holds things belonging to chart1
var url = '/forexes.json'
$.ajax({
url: url,
cache: false,
dataType: 'jsonp', //will set cache to false by default
context: localhost,
complete: function(data){
var a=JSON.parse(data.responseText);
// console.log(a);
var data_mapped = a.map(function (data){
return data.forex;
}).map(function (data) {
return {
currencyDate: data.published_at,
currencyValue: data.mean
}
});
this.currencyDate = _.pluck(data_mapped, 'currencyDate');
this.currencyValue = _.pluck(data_mapped, 'currencyValue');
console.log(this.currencyDate);
this.chart1.data.series[0].data = this.currencyValue;
this.chart1.data.xAxis.categories = this.currencyDate;
chart = new Highcharts.Chart(this.chart1.data);
}
});
localhost.chart1.data = { //js single-threaded, this obj created before callback function completed
chart: {
renderTo: "currency"
},
title: {
text: "Forex by Day"
},
xAxis: {
categories: null, //will be assigned array value during ajax callback
title: {
text: null
}
},
yAxis: {
title: {
text: "Pounds"
}
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat("%B %e, %Y", this.x) + ': ' +
"$" + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
name: 'Pound',
data: null
}
]
};
});
</script>
</div>
**** returns
this.chart1.data.xAxis.categories = ["2003-01-01T00:00:00.000Z", "2003-01-02T00:00:00.000Z", "2003-01-03T00:00:00.000Z", "2003-01-04T00:00:00.000Z", "2003-01-05T00:00:00.000Z"]
this.chart1.data.series[0].data = [147.653, 148.007, 147.971, 148.202, 148.384, 147.888]
How do I use this data to generate a highstocks line chart resembling this
In the highstock you cannot use categories, only datetime type, so you should parse your data to timestamp and use it in the data.