Highcharts don't connect points between years - highcharts

Is it possible not to connect points between years? See screenshot of graph below. I've been told it's misleading. My only solution so far is to create year end nulls for each sample year of each station. That's about 750 entries in SQL table. Seems crude. Can anyone come up with a more elegant and programmatic solution.
Data is retrieved via json from Postgresql.
Any suggestions or references would be greatly appreciated,

Gaps in series can be created through null value points.
Other option is to place data for each year in different series that will be linked together and have same color options and names.
Example: http://jsfiddle.net/kcccL6vw/1/
$(function () {
$('#container').highcharts({
xAxis: {
type: 'datetime'
},
series: [{
pointStart: Date.UTC(2013, 11, 30),
pointInterval: 3,
pointIntervalUnit: 'month',
data: [1,2,3,4,5],
name: 'Series',
id: 'S1',
color: '#fa0'
},{
pointStart: Date.UTC(2015, 0, 15),
pointInterval: 3,
pointIntervalUnit: 'month',
data: [1,2,3,4,5],
name: 'Series',
linkedTo: 'S1',
color: '#fa0'
}]
});
});

Use scatter plot instead of line chart if you dont want to connect points.
type:'scatter'

It's ugly but it works for now. I got the year range of existing data then appended records with all year end('12/31/20xx')null values to existing data. connectNulls: false prevented any points connecting to them.Then sorted the array by date which was unnecessarily difficult.
I know my JavaScript skills suck, so if anyone sees a way to tighten it up, please respond. I need all the help i can get. Here's my jsfiddle I was working from
Thanks to all for help and suggestions,
Michael
var cruiseDate = [];
for (var i = 0; i < data.length; i++) {
sampleDate = data[i][1];
thisDate = moment(sampleDate).format('MM/DD/YYYY');
cruiseDate.push([thisDate]);
}
var minDate = moment(cruiseDate[0], "MM/DD/YYYY").year();
var maxDate = moment(cruiseDate[cruiseDate.length - 1], "MM/DD/YYYY").year();
console.log('first year: ' + minDate + ' last year: ' + maxDate);
for (var i = minDate; i <= maxDate; i++) {
temp = null;
insertDate = moment('12/31/' + i).valueOf();
console.log('epoch: ' + insertDate + ' ' + moment(insertDate).format("MM/DD/YYYY"));
data.push(["year-end-null", insertDate, 0, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp])
}
function compare(a, b) { // from stackoverflow
var aDate = new Date(a[1]);
var bDate = new Date(b[1]);
if (aDate < bDate) return -1;
if (aDate > bDate) return 1;
return 0;
}
data.sort(compare);

Related

Highcharts - Indicator's data not showing in line chart

I am fetching data from an endpoint
I display the data in a highchart
There are several indicators that can be selected. For each of them another yAxis is added below the main one.
My series data are of this format :
series: [
{
data: [],
id: 'prices',
step: this.hasStep,
name: this.$props.title,
fillColor: 'rgba(127,183,240,0.2)',
},
{
visible: false,
type: 'column',
id: 'volume',
name: 'Volume_hardcoded',
//linkedTo: 'prices',
data: this.volumeSeries,
},
],
I save the data in the following way (don't pay attention in the logic, it works fine):
if (this.selectedTimeSpan.tickInterval === 1) {
for (let i = 0; i < prices.length; i++) {
let xData = null;
this.selectedTimeSpan.getIntradayData
? (xData = Math.floor(new Date(prices[i].time).getTime()))
: (xData = Math.floor(new Date(prices[i].date).getTime()));
priceSeries[i] = {
x: xData,
open: prices[i].first,
high: prices[i].high,
low: prices[i].low,
close: prices[i].last,
y: prices[i].last,
volume: prices[i].tradingVolume,
};
this.volumeSeries[i] = {
x: xData,
y: prices[i].tradingVolume,
};
}
} else {
let j = 0;
for (
let i = 4;
i < prices.length;
i += this.selectedTimeSpan.tickInterval
) {
priceSeries[j] = {
x: Math.floor(new Date(prices[i].date).getTime()),
open: prices[i].first,
high: prices[i].high,
low: prices[i].low,
close: prices[i].last,
y: prices[i].last,
volume: prices[i].tradingVolume,
};
this.volumeSeries[j] = {
x: Math.floor(new Date(prices[i].date).getTime()),
y: prices[i].tradingVolume,
};
j++;
}
}
When I select these indicators (they are based on the volume), I am getting this result.(You can see a blank space below the main chart.) Instead when i swap to OHLC or candlestick my main series (series[0]) it looks works fine and it looks like this. Any idea why is that happening? I haven't touched the tooltip settings at all (in case it was there a problem). I am struggling 2 days now with it can't really figure it out. Any help would be appreciated a lot. If you need more information feel free to comment so I can provide. Thanks in advance. Chris.
Fixed, there's a flag that can be used called usedOhlcData in series object. (series[0] in my case]. We just set it to true.
series:[{
data:[],
useOhlcData:true,
...}
,{
...
}]

Highcharts - Stack Graph Display Average of all values

I am using highcharts for statistical data displaying. I want to display , on the stack label , the average of all the values .
Below is what i am doing but i cant seem to get it right :
yAxis: {
min: 0,
title: {
text: 'Task'
},
stackLabels: {
style: {
color: 'black'
},
enabled: true,
formatter: function() {
return (this.axis.series[1].yData[this.x]).toPrecision(2) + '%';
}
}
},
The above only takes the last value on the stack and shows the percentage. For instance , if the last value is 50 , the above displays 50% as the stack value . I want to take an average of all the values. Any help would be appreciated.
If you want to show any stack's percentage mean if your stacked column has two stack A-5 and B-10 , then the % of B in column is 66% and % of A is 33%. If you want to show that use following in formatter function ( refer This Fiddle Link)
formatter: function() {
return (this.axis.series[1].yData[this.x] / this.total * 100).toPrecision(2) + '%';
}
Updating as per OP 's comment Refer Working fiddle here
Use following code : Make your data in a variable and calculate the sum
var seriesData = [{
name: 'Incomplete',
data: [1, 3, 4, 7, 20]
}, {
name: 'Complete',
data: [3, 4, 4, 2, 5]
}];
var total = 0;
$.each(seriesData,function(item){
$.each(seriesData[item].data,function() {
total += this;
});
});
And then use following in stacklabel formatter :
formatter: function() {
return ( this.total/ total * 100).toPrecision(2) + '%';
}
series:seriesData
hope it helps :)
This doesn't seem to be as easy as it should be.
I would accomplish this by pre-processing the data to generate an array of averages, and then referencing that array from the stackLabels formatter function.
Example, build the averages (assumes array 'data' with sub array for each series data values):
var sum = 0;
var averages = [];
var dataLen = data.length;
$.each(data[0], function(x, point) {
sum = 0;
for(var i = 0; i < dataLen; i++) {
sum += data[i][x];
}
averages.push(sum/dataLen);
})
And then in the formatter:
yAxis : {
stackLabels: {
enabled: true,
formatter: function() {
return Highcharts.numberFormat(averages[this.x],2);
}
}
}
Example:
http://jsfiddle.net/jlbriggs/vatdrecb/
If I could find a way to get a reliable count of the points in each stack, you could just use
return this.total/countOfPoints;
in the formatter without needing to build an array, but I can't seem to reliably get that count.

Formatting Tooltip Value on Series

I'm creating a multichart (line and column) and I need to format the tooltip value for only one of my series. The thing is: formatter doesn't seem to work inside series.
I have a point value like: 212575200
In tooltip it's being formatted into 2.125.752,00
But I need it to be formatted into: 2.1 M (for million)
(K for thousand, M for million, B for billion)
How can I format a tooltip value for only one of my series?
This is the code I'm using:
series : [{
name : ((tipoGrafico == 'line' || tipoGrafico == 'column')?'ult':' '),
data : dadosJson,
pointStart: dadosJson[0][0],
pointInterval: 24 * 3600 * 1000,
yAxis: 0, // Em qual grafico do eixo Y irĂ£o esses dados
tooltip: {
valueDecimals: CASAS_DECIMAIS,
}
},{
type: 'column',
name: nomeEstudo,
data: volume,
pointStart: dadosJson[0][0],
pointInterval: 24 * 3600 * 1000,
yAxis: 1,
tooltip: {
valueDecimals: ((nomeEstudo != "neg") ? CASAS_DECIMAIS : 0),
pointFormat: '<tspan style="color:{series.color}"> {series.name}: </tspan><tspan> ' + formatNumber(('{point.y}'/formataValores('{point.y}').divisor))+formataValores('{point.y}').letra + '</tspan>'
},
}],
Notice that I'm trying pointFormat, but It's returning a NaN from my other JS functions, because it can't figure out in time '{point.y}' is actually a Number, not a String.
In the formatter you can check which serie is displayed in the tooltip, then use condition (i.e based on the id of serie or name or index) and return content.
Following kind of function will help you:
tooltip:
{
formatter: function() {
for(var temp=0,tempLength = this.points.length;temp<tempLength; temp++)
{
//You will get the point value here by using following code
var Value = this.points[temp].y;
//Now you can apply any format to this value
}
}
}

Highcharts - Dyanmic graph with no initial data

If you open this JSFiddle with the dynamic spline update it loads the series with 20 points before it starts updating every second.
Example
I don't want to display any initial data and let the interval add the points as they come in.
So I change:
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
to
series: [{
name: 'Random data',
data: []
}]
But it doesnt add the points. Is there something I am missing?
Change your load function so that the shift parameter doesn't apply before you've added your 20 values, see this jsfiddle
load: function() {
// set up the updating of the chart each second
var series = this.series[0],
maxSamples = 20,
count = 0;
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint(
[x,y]
, true
, (++count >= maxSamples)
);
}, 1000);
}
The third parameter of addPoint is set if you what to shift a point after add this one.
So, what is happening ?
You're adding a point and then removing it.
Change:
series.addPoint([x, y], true, true);
To:
series.addPoint([x, y], true);
Demo
Reference
http://api.highcharts.com/highstock#Series.addPoint()

Highcharts, how can I start xAxis on an arbitrary time

I have a line chart with a datetime xAxis. I need to show ticks every 10 minutes, for that I have set tickInterval to 10*60*1000, my problem is that I need to show ticks every 10 minutes since the first date, for example, if my first point is displayed at 10:33, I need to show ticks at 10:33, 10:43, 10:53, etc, but what I have are ticks at 10:30, 10:40, 10:50 and so on, is there any way to do this?
Thanks!
It's not that straightforward because Highcharts automatically determines the labels to use when the x-axis is of the type 'datetime':
"In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days"
To set labels like '10:33' you need to create your own categories. Luckily these can simply be derived from your data and the desired time interval.
Here's a working example: http://jsfiddle.net/Rt7ZV/
We just take the given start date, interval and number of points and build an array of the categories to be used as the x-axis labels.
function getTimes(numTimes, interval) {
var ms = (new Date(2012, 02, 30, 10, 33)).getTime();
var times = [];
var startDate = new Date(ms);
times.push(startDate.getHours() + ":" + startDate.getMinutes());
for (var i = 1; i< numTimes; i++)
{
ms += interval;
var nextTime = (new Date()).setTime(ms);
var nextDate = new Date(nextTime);
times.push(nextDate.getHours() + ":" + pad(nextDate.getMinutes(), 2));
}
return times;
}
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
var data = [1, 2, 3, 4, 5, 3, 2, 5, 7, 6, 4];
var interval = 10*60*1000
var timeCategories = getTimes(data.length, interval);
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
zoomType: 'x',
spacingRight: 20
},
title: {
text: 'Time series'
},
xAxis: {
categories: timeCategories,
title: {
text: null
},
startOnTick: false
},
yAxis: {
title: {
text: 'Exchange rate'
},
startOnTick: false,
showFirstLabel: true
},
tooltip: {
shared: true
},
legend: {
enabled: false
},
series: [{
type: 'line',
name: 'time series',
data: [
1, 2, 3, 4, 5, 3, 2, 5, 7, 6, 4
]
}]
});
});
});
I found the tickPositions property on xAxis, which isn't documented on highcharts, only on highstock, but seems to work fine on both. With this property you can specify which values you want to hace a tick for, and work perfectly for my problem.

Resources