Data not appearing in HighChart - javascript

I am trying to create something like this resizable HighChart.
The difference is that i am loading my data from a blob.
This is the graph that i receive:
This is part of the received data, from the console.log(lines);:
[{ date: '7/13/2016 8:35:00 AM', value: 60 },{ date: '7/13/2016
8:36:00 AM', value: 45 },...]
This is my code: https://jsfiddle.net/end5xc7m/
series: [{
turboThreshold: 20000,
type: 'area',
name: 'Values to date',
data: data}
I believe this is where i am getting the problem from, in the function visitorData.
I am not having the data projected onto the graph.

As jlbriggs noted, this is due to a formatting issue. Unless you you're using categories to plot your axes, Highcharts visualizations will not draw if data are input as strings.
I've updated your fiddle with a few fixes: https://jsfiddle.net/brightmatrix/end5xc7m/2/
function processData(allText) {
var allTextLines = allText.split(/\r?\n/);
var lines = [];
for (var i = 0; i < allTextLines.length - 1; i++) {
var currentLine = allTextLines[i].split(',');
var thisLineValue = [Date.parse(currentLine[0]),parseInt(currentLine[1])];
lines.push(thisLineValue);
}
return lines;
}
Here's what I changed:
What you want to pass along to your chart is a set of arrays like [x,y], where these variables are either dates or numbers. Building the values using curly braces and + concatenation operators turns these into strings. So, instead, I created a temporary array called thisLineValue and pushed that to your lines array.
Next, within that temporary array, I used Date.parse() to turn your date values into timestamps. This is happily understood by Highcharts for datetime axes, as you set with your x-axis.
For your y-axis value, I used parseInt() to avoid those values being turned into strings as well.
Finally, I removed the toString() function when you return the lines array to the chart. Again, this keeps the values in the format the chart is expecting (dates and numbers).
I hope this is helpful for you!

Related

weird series sorting problem in Highcharts bar chart

Full code example here: https://jsfiddle.net/_dario/o6nugkrw/24/
I have a data series structured like this (from an API call):
{
"mango": 12736,
"orange": 8906,
"banana": 8404,
"2020": 8239,
"blackberry": 7703,
"pear": 7297,
"raspberry": 6895,
"apple": 6432,
"kiwi": 6202,
"tomato": 6189,
"1995": 6123,
"kumquat": 6038,
"melon": 5982,
"strawberry": 5973,
"pineapple": 5441
}
The sorting order is value high to low, regardless of the label. These are to be plotted in an Highcharts horizontal bar chart.
Notice there are two numeric (string, though) labels: "1995" and "2020".
This specific data format is then parsed for Highcharts:
//--previous highcharts options
series: Object.keys(data).map((s, index) => {
let arr = new Array(length).fill(null, 0, length);
arr[index] = data[s];
return {
name: s,
data: arr,
tooltip: {
headerFormat: ''
},
}
}),
//--subsequent highcharts options
as per the jsfiddle example (https://jsfiddle.net/_dario/o6nugkrw/24/), the sorting order along the Y axis in the chart is different, and no matter what the order the data is presented in, the two "numeric" labels always stay on top and are sorted differently (by numeric value).
I found no reference in the Highcharts docs about this and would like to have them treated as "words" like the others and sorted accordingly. I believe the error might be in the parsing above, but cannot find it.

Chart.js - consolidating days to month totals along the x (time) axis?

I'm feeding two daily statistics datasets into my chart. As you can see, each element represents the value for a particular day.
"data":[[{"y":"1", "x":"2018-04-01T04:00:00Z"},
{"y":"14", "x":"2018-04-02T04:00:00Z"},
{"y":"5", "x":"2018-04-03T04:00:00Z"},
{"y":"7", "x":"2018-04-04T04:00:00Z"},
...
The x axis is defined as follows:
xAxes: [{
type: 'time',
distribution: 'series',
time: {
unit: 'month'
}
}]
I (naively?) thought that the chart would be rolling up (summing) the day values into the appropriate month buckets but that's not what I got. Instead, I got monthly tick marks along the x-axis but data points are plotted within the chart at daily precision. (See screenshot.)
Before I go ahead and reprocess my dataset to manually roll up days into their respective month buckets, I'd like to hear whether the chart can in fact do this for me but I'm just setting this up wrong, or whether I do in fact need to take care of this summarization myself, before supplying the dataset to the chart for plotting.
Thanks for your advice!
I solved this by doing the rollup myself during the assembly of the underlying dataset which is then supplied to the chart.
var dayDate = new Date($scope.insights.locationMetrics[lm].metricValues[metric].dimensionalValues[dim].timeDimension.timeRange.startTime);
var monthDate = dayDate.getFullYear() + "-" + (dayDate.getMonth() + 1);
var hitCount = {
y: $scope.safeNumber($scope.insights.locationMetrics[lm].metricValues[metric].dimensionalValues[dim].value),
x: monthDate
}
var alreadyRecorded = hits[labelIdx].findIndex(obj => obj.x == hitCount.x)
if (alreadyRecorded > -1) {
hits[labelIdx][alreadyRecorded].y += Number(hitCount.y);
}
else {
hits[labelIdx].push(hitCount);
}
Extract the date from the underlying data source
Extract yyyy-mm from the date
Create the hitCount object
Check if the hitCount object is already in the array
If the object is already in the array then increment the hitCount (y) within the array.
Otherwise, push the object into the array.

How to limit chart xAxis date range in HighCharts?

The data series in my HighCharts chart only includes dates from the past few days, but the chart's x-axis and zoom bar show a date range all the way back to 1970.
How can I limit the presented date range so it only goes back as far as the first date present in the series data?
Example
HTML
<div id="chart_container" style="height: 500px></div>
JavaScript
$(function () {
var timestamps = [1481000484000,1481108510000,1481215541000,1481316568000,1481417583000];
var series_raw_data = [100,300,750,400,200];
// prepare data
var points = [[],[]];
for (var i = 0; i < timestamps.length; i++) {
points.push([timestamps[i], series_raw_data[i]]);
}
// create chart
$('#chart_container').highcharts('StockChart', {
series: [{
data: points
}]
});
});
Here's Fiddle1 which shows the behavior.
I also tried setting the xAxis 'min' option to the first timestamp, and setting the axis type to 'datetime', but those didn't help - Fiddle2.
The reason why it happens is your points array.
If fact, after filling, it looks like this:
points = [ [], [], [x, y], [x, y]]
Those two empty arrays create unwanted behaviour.
Fix the initial array and it works
var points = [];
example: https://jsfiddle.net/hbwosk3o/3/

Highcharts JSON decimal data format issue

I'm trying to solve an odd problem. I'm getting a json array back from an ajax call and I'm attempting to plot it in highcarts. I've mapped other graphs from the same array and all is well, up until the point I hit decimal numbers (maybe co-incidence). In this case the dates show fine but the y-axis (prices) is empty.
Now, I can 'alert(s5)' and the data displays on the alert box as it should.
I also ran a consol log and see "["5.15", "4.94", "4.43", "4.49", "4.42", "4.41"]" (maybe the " in the numbers is causing the issue!?)
If I put the values manually into the highcharts data it works perfectly but I just can't assign the array to a value and get it to display.
code looks like:
function draw_flow(garray)
{
var obj = JSON.stringify(garray);
obj = JSON.parse(obj);
s5 = obj["closeprice"][0];
ticks = obj["date"][0];
alert(s5); //THIS DISPLAYS DATA FINE! "5.15,4.94,4.43,4.42,4.41"
$('#chart3').highcharts({
chart: {
marginBottom: 80
},
xAxis: {
categories: ticks
},
yAxis: {
labels: {
align: 'left',
x: 0,
y: -2
}
},
series: [{
data: s5 //This does not work
//data: [5.15,4.94,4.43,4.42,4.41] //this works
}]
});
}
You are correct. The reason the Y axis is not displaying is because of the Strings in your data. (which should be read as numbers)
You have to convert your data from Strings to an array of numbers which can be achieved with the following
s5 = s5.map(Number);
This is an example jsFiddle which shows it in action http://jsfiddle.net/e803sjsp/
A bit cheeky but have you checked that s5 is actually an array and not a string of comma separated values. You might want to try a console.log to be sure..

Highcharts: passing additional information to a tooltip

I have an array of data points that I am passing to a Highcharts chart that looks like
mydata = [{
x: 1,
y: 3,
nameList: ["name1", "name2"]
}, {
x: 2,
y: 4,
nameList: ["name3", "name4"]
}]
I build the chart like this:
$("#chart").highcharts("StockChart", {
series: [{
data: mydata
}, {
data: yourdata
}]
});
Now, I would like to be able to access the nameList array from the shared tooltip, which I'm trying to do as follows:
tooltip: {
formatter: function() {
var s = "";
$.each(this.points, function(i, point) {
s += point.point.nameList;
});
return s;
},
shared: true
}
but when examining the point objects in Firebug using console.log(point), I can't seem to find the nameList entry anywhere in them. How could I access this auxiliary information in a shared series tooltip? All help is appreciated.
Eureka!
By default, Highcharts will accept several different types of input for the data of a series, including
An array of numerical values. In this case, the numberical values will be interpreted
and y values, and x values will be automatically calculated, either starting at 0 and
incrementing by 1, or from pointStart and pointInterval given in the plotOptions.
An array of arrays with two values. In this case, the first value is the x value and the
second is the y value. If the first value is a string, it is applied as the name of the
point, and the x value is incremented following the above rules.
An array of objects with named values. In this case the objects are point configuration
objects as seen below.
However, the treatment of type 3 is different from types 1 and 2: if the array is greater than the turboThreshold setting, then arrays of type 3 won't be rendered. Hence, to fix my problem, I just needed to raise the turboThreshold setting like so:
...
plotOptions: {
line: {
turboThreshold: longestArray.length + 1
}
},
...
and the chart renders the longestArray data properly. Hurray! The only drawback is that there is a considerable time spent rendering the data for much longer arrays due to "expensive data checking and indexing in long series." If any of you know how I might be able to bypass this checking or otherwise be able to speed up the processing of this data, I'd be extremely thankful if you'd let me know how.
I can see it here:
tooltip: {
formatter: function() {
var s = "";
console.log(this.points[0].point.nameList); // ["name1", "name2"]
$.each(this.points, function(i, point) {
s += point.point.nameList;
});
return s;
},
shared: true
}

Categories

Resources