I'm trying to make visualization of the voltage, Array has 1k elements but I'm testing it on first 10 for now, the thing is that It doesn't display anything, what's more interesting when I use fake date which is commented out now, It shows chart properly. I thought that perhaps there is some problem with array so tried to use Array.from but it also brought no effect, here is my code:
.then(function(res) {
var averageVoltage = []
var inputVoltage = []
var date = []
for (var i = 0; i < 10; i++) {
if (res[i].average_volatage !== undefined) {
averageVoltage.push(res[i].average_volatage)
date.push(res[i].timestamp)
}
}
console.log(averageVoltage)
console.log(date)
Highcharts.chart('battery_chart', {
chart: {
type: 'line'
},
title: {
text: id
},
yAxis: {
title: {
text: 'Measurement'
},
},
xAxis: {
categories: date
},
series: [{
name: 'Average Voltage',
data: averageVoltage
// data: [12283, 12283, 12281, 12280, 12282, 12283, 12281, 12282, 12281, 12280]
},
]
});
and that's how array is shown in console.log:
Your array should show up as [12283, 12281, 12280, etc.] in console as well, instead it shows up as [Number, Number, ...]. Try changing this line:
averageVoltage.push(res[i].average_volatage)
to:
averageVoltage.push(parseInt(res[i].average_volatage))
Additionally, instead of using dates as categories, it could be easier to use the highchart datetime axis. This would let you manipulate how you want the date displayed, have several series with different timestamps in one graph, and many other things. To get this to work, you could do this:
.then(function(res) {
var averageVoltage = []
var inputVoltage = []
for (var i = 0; i < 10; i++) {
if (res[i].average_volatage !== undefined) {
averageVoltage.push({x: new Date(res[i].timestamp).getTime(), y: parseInt(res[i].average_volatage)})
}
}
console.log(averageVoltage)
Highcharts.chart('battery_chart', {
chart: {
type: 'line'
},
title: {
text: id
},
yAxis: {
title: {
text: 'Measurement'
},
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Average Voltage',
data: averageVoltage
},
]
});
Related
in the database I have 3 data which i send via Rest-API to the Frontend Angular.
This works fine.
Here in browser console, you can see all three dataset, which I get through node.js via Rest-API:
How it looks in the browser console
the result in the browser console looks like this:
0:
device_id: 2885679
list: Array(1)
0:
dt: 1596608643
main:
humidity: 10
pressure: 7.86
temp: 120.052
temp_max: 40.052
temp_min: 20.052
__proto__: Object
__proto__: Object
length: 1
__proto__: Array(0)
message: "1"
__v: 0
_id: "5f2a63857ce17d64d49465a4"
In the typescript component xy.component.ts my code looks like this:
export class ContactsComponent {
chart: any = [];
constructor(private contactService: ContactService) { }
ngOnInit() {
this.contactService.getContacts()
.subscribe((res: any[]) => {
console.log(res);
for (let i = 0; i < res.length; i++) {
let temp_max = res[i]['list'].map(res => res.main.temp_max);
let temp_min = res[i]['list'].map(res => res.main.temp_min);
let alldates = res[i]['list'].map(res => res.dt)
console.log(alldates)
let deviceData = []
alldates.forEach((res) => {
let jsdate = new Date(res * 1000)
deviceData.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
})
console.log(deviceData)
this.chart = new Chart('canvas', {
type: 'line',
data: {
labels: deviceData,
datasets: [{
data: temp_max,
borderColor: '#3cba9f',
fill: false
}, {
data: temp_min,
borderColor: '#ffcc00',
fill: false
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}]
}
}
})
}
})
}
Why console.log(deviceData) only return the last value of the iteration?
I want to return all the values in console.log(devicedata) to draw a graph based on 3 timestamps. Here when I only get back 1 timestamp. Somehow it overwrites the values with the deviceData.push - Methode.
My goal is to draw all the datapoints i have (refer to the screenshots of the browser console).
Here how the graph is plot in the browser. It only plots one point, that is exactly the point of the console.log(deviceData):
graph
What is the problem and how can I fix it?
Thanks
Eden
It seems every object in res has a list with only a single item.
(res[i]['list'] is an array of length 1)
Try logging this:
(this takes all the values of each item and puts them in a single list)
let allvalues = [];
for (const item of res) {
for (const measurement of item.list) {
allvalues.push(measurement)
}
}
console.log(allvalues);
I cant save data in localstorage, I get the result [object Object],[object Object],[object Object]
Here is the code
var usersonline = null;
var maxonline = 50;
Highcharts.stockChart('container', {
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.round(usersonline);
series.addPoint([x, y], true, false);
}, 1000);
}
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'hour',
text: '1H'
}, {
count: 3,
type: 'hour',
text: '3H'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 2
},
title: {
text: 'Live Chart of Players Online'
},
exporting: {
enabled: false
},
yAxis: {
title: 'Players Online',
min: 0,
plotLines: [{
color: 'red', // Color value
label: {
text: "Max Player Line"
},
value: maxonline, // Value of where the line will appear
width: 2 // Width of the line
}]
},
series: [{
name: 'Players Online',
connectNulls: false,
data: (function () {
var data = [],
time = (new Date()).getTime(),
i;
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("chartdata") === null) {
localStorage.setItem('chartdata',[])
data = []
console.log("No Data Found, Creating Some!")
} else {
data = JSON.parse(localStorage.getItem('chartdata'))
console.log("Chart Data Loaded.")
}
} else {
console.log("localStorage is not Supported. Saving Chart Data will not work.")
}
// generate an array of random data
window.onbeforeunload = function(){
console.log("Chart data Saved")
localStorage.chartdata = JSON.stringify(data)
}
return data;
}())
}],
lang: {
noData: "No Data."
},
noData: {
style: {
fontWeight: 'bold',
fontSize: '40px',
color: '#303030'
}
}
});
If I refresh the page it shows the chart as blank and It doesnt display "No Data" so there is data there but it is broken. What I want to happen is When I refresh the page it will keep the data, even when the browser or computer gets restarted.
Is there any solution to this problem, I tried multiple ways but none of them work.
This is a live data chart that I need to save data so The Chart doesnt go blank if you accidently refresh the page.
So the reason why when you get the item it says [Object object] is because localStorage.setItem accepts a DOMString, not an object. setItem will use toString to coerce values into a string, and Object.prototype.toString will always be [object Object].
https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
You need to use JSON.stringify to convert your array into a valid JSON string in your localStorage.setItem function call and then use JSON.parse to parse that string when you use localStorage.getItem.
const loki = { "type": "dog", "name": "Loki" }
// Sets [object Object] in local storage
localStorage.setItem("lokiKey", loki)
// Sets "{"type":"dog","name":"Loki"}" in local storage
localStorage.setItem("lokiKey", JSON.stringify(loki))
Hope this helps!
Did you try to use myChart.addSeries ? If Series have been changed you should calling method redraw
I'm trying to load a csv and format it so it will display as a chart in highcharts, this is proving difficult because of the structure of the csv data.
Here is the csv: https://pastebin.com/Ynz7GJJh
Sample:
iso,type,year,affected
JAM,Earthquake,1907,90000
JAM,Storm,1912,94820
TON,Volcano,1946,2500
DZA,Earthquake,1954,129250
HTI,Storm,1954,250000
Here is my highcharts.ajax so far
var hsOptions = {
chart: {
type: 'column'
},
title: {
text: 'KEY NATURAL HAZARD STATISTICS'
},
subtitle: {
text: 'Number of People Affected'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
Highcharts.ajax({
url: '/pathto.csv',
dataType: 'text',
success: function(csv) {
var rows = csv.split(/\r\n|\n/);
var cell;
var series = [];
var seriesBuilder = {name: countryValue, data: []};
for (var i = 0; i < rows.length; i++) {
cell = rows[i].split(',');
if (cell[0] === countryValue){
seriesBuilder.data.push(cell);
}
}
console.log(seriesBuilder);
series.push(seriesBuilder);
hsOptions.series.push(series);
Highcharts.chart('hazard-stats', hsOptions);
},
error: function (e, t) {
console.error(e, t);
}
});
which does make this
But I need this to build a series per disaster type, then the years have to combine on their own axis... it should be able to render just like this:
I am using Highcharts and i currently have 2 arrays which I would like to stop reading from and start reading the data from my object.
Here is the code i currently have:
items = ['Item 1', 'Item 2'];
Quantity = [10 , 5];
jQuery('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
categories: mydata
},
title: {
text: 'Items Title'
},
series: [{
name: 'Items',
data: Quantity
}],
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}<br/>',
shared: true
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function () {
console.log('Clicked');
},
},
},
},
},
});
The above displays 2 items of height 10 and 5.
Now what I need to do is to be able to read this data instead:
var mydata = {
"items":[{
"id":"123",
"name":"item name here",
"subitems":[{
"id":"567",
"name":"subitem 1"
},
{
"id":"657",
"name":"subitem 2"
}],
"somthing here":null,
},
{
"id":"456",
"name":"item name here too",
"subitems":[{
"id":"567",
"name":"subitem here"
},
{
"id":"657",
"name":"subitem here roo"
}],
"somthing here":null,
}]
};
The quantity values need to be the subitems count so in the case of the data above it would be 2,2
How can I do this?
This should get you started:
https://jsfiddle.net/b3wii/0Lx77f1a
If you click on a column it reads the mydata and displays the subitems. To get the subItem count just use mydata.items[i]['subitems'].length. To update the existing Item values change currentItemY or currentItemX.
click: function (e) {
if(this.series.name != 'SubItems'){
let currentItemName = items[this.index];
let currentItemY = this.y;
let currentItemX = this.x;
let newCategories = [];
let newSeries = [];
for(let i in mydata.items){
if(mydata.items[i]['name'] == currentItemName){
for(let j in mydata.items[i]['subitems']){
newCategories.push(mydata.items[i]['subitems'][j]['name']);
newSeries.push(mydata.items[i]['subitems'][j]['quantity']);
}
}
}
chart.update({
xAxis: {
categories: newCategories
},
series: [{
name: 'SubItems',
data: newSeries
}]
});
}
},
I am trying to write code this way in perl.
\$('#AmpCovPlot').highcharts({
var amp_name = new Array[$amp];
var amp_cov = new Array[$cov]
chart: {
type: 'line'
},
title: {
text: 'Average cov'
},
xAxis: {
categories: [amp_name]
},
yAxis: {
title: {
text: 'Amp name'
}
},
series: [{
name: [amp_name]
data: [amp_cov]
}]
});
so $amp and $cov are perl variables containing array elements, generated by statement :
my $Cov=join(",",#cov);
And I am getting "Uncaught SyntaxError: Unexpected Identifier". I know I am doing a blunder, and I am new to javascript.
Can somebody let me know how to fix this?
Thanks!!!
"Unexpected Identifier" is a hint for invalid Javascript. In your case, i think you print the Javascript Code without double quotes qq{}, to be more precise: You print a $ where no $ is allowed or you dont print a $ where a $ is expected.
When you just Copy + Pasted your Javascript code, you have a syntax Error as well:
var amp_cov = new Array[$cov] // no semicolon ;
// what is the following part for? you dont really assign that stuff to
// something .... seems wrong
chart: {
type: 'line'
},
title: {
text: 'Average cov'
},
xAxis: {
categories: [amp_name]
},
yAxis: {
title: {
text: 'Amp name'
}
},
series: [{
name: [amp_name]
data: [amp_cov]
}]
The next part is the join of the Perl Array. You need to quote the Variables inside the Javascript as well:
var array = ['a','b','c'];
So your join need to be something like:
my $cov = join q{,}, map {qq{'$_'}} #cov;
Which just mean, that you first add single quotes to each element in #cov and then join all with ,
You are defining variables inside object, which is not proper for JS:
$('#AmpCovPlot').highcharts({
var amp_name = new Array[$amp]; // not here!
var amp_cov = new Array[$cov] // not here!
chart: {
type: 'line'
},
title: {
text: 'Average cov'
},
xAxis: {
categories: [amp_name]
},
yAxis: {
title: {
text: 'Amp name'
}
},
series: [{
name: [amp_name]
data: [amp_cov]
}]
});
This should be done this way:
var amp_name = new Array[$amp]; // here define variables
var amp_cov = new Array[$cov]; // here define variables
$('#AmpCovPlot').highcharts({ ... }); // and create chart