Is it possible to plot "live data" in R language? - javascript

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();

Related

plotly.js page render is super slow with 10 charts in DOM. firefox freezes. whats wrong?

I am getting super slow page loads (~10s on chrome, ~15 using firefox) when rendering a page with 10 Plotly charts (lines and bars) with very few data points on each chart (<100 per chart).
I'm not getting any errors, and my js code runs in ~300ms without errors (i used console.log() with timestamps). there is no network activity whilst waiting for the charts to render.
Am I doing something wrong?
The charts are rendered using a loop which calls a function with different parameters:
ajax call:
$.ajax({
method: "GET",
url: '/app/api/dashboard/data',
success: function(payload){
console.log('starting bal hist')
var bal_hist = JSON.parse(payload.balance_history);
balanceHistoryChart(elementID='balanceHistory', data=bal_hist);
console.log('ending bal hist')
var data = JSON.parse(payload.aggregated);
data = data.map(function(object) {
object.value_date = new Date(object.value_date);
return object
})
var allCategories = data.map(x => x.category);
var categories = new Set(allCategories);
console.log('starting loop')
for (var category of categories){
var chartID = category.toLowerCase().replace(' ','_') + '_chart';
console.log('starting catChart')
catChart(elementID=chartID, category=category, data=data)
console.log('ending catChart')
}
console.log('end loop')
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function that creates the plotly charts:
function catChart(elementID, category, data) {
let filterForCat = data.filter(obj => obj.category === category);
let dates = filterForCat.map(function(obj) {
return obj.value_date
});
let weeklyTotal = filterForCat.map(function(obj) {
return obj.weekly_total
});
let movingAv = filterForCat.map(function(obj) {
return obj.moving_av
});
var movingAvSeries = {
type: "scatter",
mode: "lines",
name: '4-week average',
x: dates,
y: movingAv,
line: {color: 'green'}
};
var weeklyTotalSeries = {
type: "bar",
name: 'weekly totals',
x: dates,
y: weeklyTotal,
line: {color: 'red'}
};
var layout = {
showlegend: false,
title: false,
margin: {
l: 30,
r: 20,
b: 20,
t: 20,
pad: 5
},
};
var data = [ movingAvSeries, weeklyTotalSeries ];
var config = {
responsive: true,
displayModeBar: false,
};

ChartJs - displaying data dynamically from back-end

I have been struggling with this one for days now, really need some help. I need to apply gradient colors and some custom styling to our ChartJs bar chart, that contains call reporting data which comes from the back-end server. I found a way how to apply the styles and gradients, but can't figure out how to configure datasets to display correct data from the server, instead of some random numbers (eg. 10,20,30), like I tried for gradientGreen below. Any ideas?
//main html
<div class="row mb-4 mt-4">
<div class="col-9">
<h4 class="text-center">Call Distribution</h4>
#await Component.InvokeAsync("HourlyCallTotals", new { from = Model.From, to = Model.To, customer = Model.customer, site = Model.site })
</div>
//component html
#model CallReporter.ViewModels.BasicFilter
<div id="hourlyChart">
</div>
<script>
var HourlyCallData = #Html.RenderAction("HourlyTotals", "Calls", "", new { from = Model.from.ToString("s"), to = Model.to.ToString("s"), customer = Model.customer, site = Model.site })
</script>
//relevant part of JS function for Chart
function hoursChartAjax() {
var hourlyChart = $('#hourlyChart').html('<canvas width="400" height="300"></canvas>').find('canvas')[0].getContext('2d');
// set gradients for bars
let gradientGreen = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientGreen.addColorStop(0, '#66d8b0');
gradientGreen.addColorStop(1, '#1299ce');
let gradientBlue = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientBlue.addColorStop(0, '#1299ce');
gradientBlue.addColorStop(1, '#2544b7');
if (hourlyChart !== undefined) {
$.get(base + "Calls/HourlyTotals", { from: from.format(), to: to.format(), customer: currentCustomer.id, site: currentSite }, function (data) {
// set the default fonts for the chart
Chart.defaults.global.defaultFontFamily = 'Nunito';
Chart.defaults.global.defaultFontColor = '#787878';
Chart.defaults.global.defaultFontSize = 12;
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: ['6AM', '9AM', '12AM', '3PM', '6PM', '9PM', '12PM'],
datasets: [
{
label: 'Total outgoing calls',
backgroundColor: gradientBlue,
data: HourlyCallData
},
{
label: 'Total incoming calls',
backgroundColor: gradientGreen,
data: [10, 20, 30]
}
]
},
//relevant part of back-end code that returns call data as Json
totalsContainer.Totals = allCallsHourly.OrderBy(x => x.Date).ToList();
return Json(new
{
labels = totalsContainer.Totals.Select(x => x.Date.ToString("hh tt")),
datasets = new List<object>() {
new { label = "Total Outgoing Calls", backgroundColor = "#1299CE", data = totalsContainer.Totals.Select(x => x.TotalOutgoingCalls) },
new { label = "Total Incoming Calls", backgroundColor = "#00B050", data = totalsContainer.Totals.Select(x => x.TotalIncomingCalls) } }
});
Attached img with console log and error, after trying solution below:
If the data comes formatted in the right way, you can just write this:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: data: data
}
If not you could do it like so:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: data.labels,
datasets: [
{
label: data.datasets[0].label,
backgroundColor: gradientBlue,
data: data.datasets[0].data
},
{
label: data.datasets[1].label,
backgroundColor: gradientGreen,
data: data.datasets[1].data
}
]
}
}

How can I plot Charts w/ time x axis from JSON and MySQL in Chart.JS?

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);
},
});
});

Decide which serie goes into range-selector highstock

I have a chart with 3 different series and I've included Range Selector from Highstock. I want to be able to select which one of the 3 series is the one set in the Range-Selector. Is there any way to dynamically assign the serie to the Range Selector?
I create the chart with 3 series like this:
//A,B,C data array
Highcharts.stockChart('container', {
series: [
{ data: A },
{ data: B },
{ data: C }
]
});
What I want to accomplish is to be able to select either A,B or C as the serie active to see in the Range-Selector preview.
Here's a jsfiddle: https://jsfiddle.net/usvonfjh/1/
You can show each series in navigator by setting series.line.showInNavigator = true. To set it dynamically use series.update() method where you can pass new options for series.
Code:
let dates = [1496268000000, 1504216800000, 1512082800000, 1519858800000, 1527804000000, 1535752800000, 1543618800000, 1551394800000, 1559340000000, 1567288800000];
let aSerie = dates.map((e, i) => [e, i < 5 ? null : i]);
let bSerie = dates.map((e, i) => [e, i + 1]);
let cSerie = dates.map((e, i) => [e, i * 2]);
Highcharts.stockChart('container', {
chart: {
events: {
load: function() {
const chart = this;
setTimeout(() => {
chart.series[1].update({
showInNavigator: false
});
}, 2000);
}
}
},
rangeSelector: {
verticalAlign: 'top'
},
series: [{
name: "aSerie",
showInNavigator: true,
data: aSerie
}, {
name: "bSerie",
showInNavigator: true,
data: bSerie
}, {
name: "cSerie",
showInNavigator: true,
data: cSerie
}]
});
Demo:
https://jsfiddle.net/BlackLabel/pxw09zrc/
API reference:
https://api.highcharts.com/highstock/series.line.showInNavigator
https://api.highcharts.com/class-reference/Highcharts.Series#update

How to plot a highstock single line series graph from ajax data

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.

Categories