Range Slider not working properly in Plotly.js - javascript

I want to be able to get range slider and a selector in my graph, I have followed the example in the documentation, but I’m getting the following error:
1.- The selector dates, are still using ‘backwards’, as opposed to ‘todate’, which is a bit weird, perhaps is the fact that I'm not understanding this 100%, but I would like to get 6 and 12 months from today, is there a way to use a forward from the earliest date period?
https://jsfiddle.net/jt1o26bd/
var Deals = {
x: {{ deals_plot.lic_deals_date|safe }},
y: {{ deals_plot.lic_deals_licenses }},
name: 'Active Licenses',
type: 'bar',
marker: {
color: 'rgb(0,131,117)',
}
};
var Leads = {
x: {{ deals_plot.lic_leads_date|safe }},
y: {{ deals_plot.lic_leads_licenses }},
name: 'Potential Licenses',
type: 'bar',
marker: {
color: 'rgb(160,220,210)',
}
};
var data = [Deals,Leads];
var layout = {
title: 'Software Licenses Term',
barmode: 'stack',
xaxis: {
autorange: true,
rangeselector: {buttons: [
{step: 'all'},
{
count: 1,
label: 'YTD',
step: 'year',
stepmode: 'todate'
},
{
count: 6,
label: '6m',
step: 'month',
stepmode: 'todate'
}
]},
rangeslider: { },
type: 'date',
tickfont:{
size: 14
},
},
yaxis: {
tickfont:{
size: 14
}
}
};
Could anyone let me know what is going on?

You might already understand the difference between backward and todate but backward will go back by exactly the count number of steps, and todate will go back by whatever amount of time is needed to round to the first count number of steps.
For example, the expected behavior of the YTD button constructed with arguments count: 1, step: 'y', stepmode: 'todate' will be to go back to Jan 1 of from the year at the end of your current daterange. Your jsfiddle does indeed do this:
If you were to construct your YTD button with stepmode: 'backward', then when you click on the button, the daterange would instead move back to Nov 2022.
Since you asked about buttons going forward in time instead of backward, this feature does not currently exist in plotly according to this forum post, but #scoutlt appears to have solved the problem for themselves by modifying their local version of plotly.js - however their solution is no longer up to date with the latest version of the library.
If you go into plotly.js/src/components/rangeselector/get_update_object.js you can see that there is a function called getXRange where the backward and todate are defined:
function getXRange(axisLayout, buttonLayout) {
var currentRange = axisLayout.range;
var base = new Date(axisLayout.r2l(currentRange[1]));
var step = buttonLayout.step;
var utcStep = d3Time['utc' + titleCase(step)];
var count = buttonLayout.count;
var range0;
switch(buttonLayout.stepmode) {
case 'backward':
range0 = axisLayout.l2r(+utcStep.offset(base, -count));
break;
case 'todate':
var base2 = utcStep.offset(base, -count);
range0 = axisLayout.l2r(+utcStep.ceil(base2));
break;
}
var range1 = currentRange[1];
return [range0, range1];
}
Personally, I think the best solution would be to define another case called forward which does the opposite of backward:
switch(buttonLayout.stepmode) {
case 'backward':
range0 = axisLayout.l2r(+utcStep.offset(base, -count));
break;
case 'forward':
range0 = axisLayout.l2r(+utcStep.offset(base, count));
break;
case 'todate':
var base2 = utcStep.offset(base, -count);
range0 = axisLayout.l2r(+utcStep.ceil(base2));
break;
}
However, I haven't worked much with the plotly.js repo, and there is the possibility that this will cause a breaking change (and might break one or more of the unit tests, for example).
If that is the case, you can do something similar to what #scoutlt did in the forum post, and change the definition of backward to mean forward (personally i think this is a pretty hacky approach, so I would only do this if defining forward doesn't work, and you want your buttons to ONLY go forward). That would look something like:
switch(buttonLayout.stepmode) {
case 'backward':
range0 = axisLayout.l2r(+utcStep.offset(base, count));
break;
case 'todate':
var base2 = utcStep.offset(base, -count);
range0 = axisLayout.l2r(+utcStep.ceil(base2));
break;
}

Related

How to count prediction (forecasting) in highchart only with data behind the last plotline?

I have a code for standard area-spline highchart where I made a function for prediction based on previous data. Prediction / forecasting is showing next 4 values in a trendline where the first prediction point is counting with real data, second point with real data plus first prediction point and the next two points about the same plus previous predictions. Otherwise it would be only a line with same values. But my data are increasing so the forecasting must be about the same.
Data in highchart are connected to Microsoft SQL Server.
Prediction is based on this code, just with few changes:
Forecast formula from Excel in Javascript
The highchart is now showing increasing data (values of resistance) as a decimal in yAxis and datetime in xAxis. Prediction is working as well but the thing is that not all data are relevant.There is always a point which is very different (lower than previous) and thats the place from where I need to count new prediction. The plotline is generated in the last high value, then starting the new (low) - and that is from where I need to count.
So here is what I do have:
-the function 'average' is counting average from values
-second function 'forecast' as you can expect is counting the forecasting (based on the code from link above)
-third function 'test' is already putting all together
-the 'results' (2,3,4) are the counted points of prediction
-'vlastnidata' are the data from mssql
-'datumek' is for the date
Now the condition for plotline (as you can see there) is that the previous point in chart must be 20 higher and then the plotline is generated - this is also working, just need to find a way how to count only with new data behind the plotline.
And here you can reach the connection function to mssql in php - if needed
Is there a way how to dynamically create a plotline in highchart when the value is lower than previous one?
As I said everything is working, plotlines and the prediction. But to see clear prediction I need to count only with relevant data.
Hope everything is clear. Thank you in advance for any recommendations.
function average(ar)
{
var r=0;
for (i=0;i<ar.length;i++)
{
r = r+ar[i];
}
return r/ar.length;
}
function forecast(x, ky, kx)
{
var i=0, nr=0, dr=0,ax=0,ay=0,a=0,b=0, result=0;
ax=average(kx);
ay=average(ky);
for (i=0;i<kx.length;i++)
{
nr = nr + ((kx[i]-ax) * (ky[i]-ay));
dr = dr + ((kx[i]-ax)*(kx[i]-ax))
}
b=nr/dr;
a=ay-b*ax;
result = (a+b*x);
return result;
}
function test(container,nazev,rtop,vlastnidata,colorSeries)
{
var result = 0, result2 = 0, result3 = 0, result4 = 0, datumek=[],hodnoty=[];
for (a=0;a<vlastnidata.length;a++)
{
datumek[a]=vlastnidata[a][0];
hodnoty[a]=vlastnidata[a][1];
}
kalkulace=(datumek[vlastnidata.length-1]-datumek[vlastnidata.length-2]);
hodnoty_nove=hodnoty;
datumek_nove=datumek;
result = forecast((datumek[vlastnidata.length-1]+kalkulace), hodnoty, datumek);
hodnoty_nove[hodnoty_nove.length]=result;
datumek_nove[datumek_nove.length]=(datumek[vlastnidata.length-1]+kalkulace);
result2 = forecast((datumek[vlastnidata.length-1]+2*kalkulace), hodnoty_nove, datumek_nove);
hodnoty_nove[hodnoty_nove.length]=result2;
datumek_nove[datumek_nove.length]=(datumek[vlastnidata.length-1]+2*kalkulace);
result3 = forecast((datumek[vlastnidata.length-1]+3*kalkulace), hodnoty_nove, datumek_nove);
hodnoty_nove[hodnoty_nove.length]=result3;
datumek_nove[datumek_nove.length]=(datumek[vlastnidata.length-1]+3*kalkulace);
result4 = forecast((datumek[vlastnidata.length-1]+4*kalkulace), hodnoty_nove, datumek_nove);
Highcharts.chart(container, {chart: {type: 'areaspline',
events: {
load:function(){
let points = this.series[0].points;
let plotLines = [];
console.log(this)
let previousPoint = points[0];
points.forEach(function(point) {
if(point.y < previousPoint.y/100*80) {
plotLines.push({
value: previousPoint.x,
color: 'red',
width: 3
});
}
previousPoint = point;
});
this.xAxis[0].update({
plotLines: plotLines
})
}
}
},
title: {text: 'Average of resistance per month, '+rtop},
legend: {layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 150,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'},
xAxis: { type: 'datetime'},
yAxis: {title: {text: 'Resistance: in ohms'}},
tooltip: {shared: true,valueSuffix: ' ohms',valueDecimals: 2},
credits: {enabled: false},
plotOptions: {areaspline: {fillOpacity: 0.5}},
series: [{ name: nazev,
color: colorSeries,
data: vlastnidata},
{name: 'Prediction',
color: '#001a33',
data: [[(datumek[vlastnidata.length-1]+kalkulace),result], [(datumek[vlastnidata.length-1]+2*kalkulace),result2], [(datumek[vlastnidata.length-1]+3*kalkulace),result3], [(datumek[vlastnidata.length-1]+4*kalkulace),result4]]
}]
});
}

Controlling the the spacing between the series to avoid cluttering in Highcharts

In the highcharts example above suppose I have 100 series in Bananas which is 1 right now and just one series in Apples ,and if there is a lot of empty space between Bananas and Oranges can we reduce the spacing between them ?
The reason is if there are 100 series in Bananas due to space constraint every line gets overlapped even though there is extra space available between Bananas and Apples . Also is it possible to remove "Oranges" if it doesnt have any series at all and accomodate only series from "Bananas"?
Categories functionality works only for constant tick interval equaled to 1. What you're trying to achieve is having a different space reserved for every category. That means that tick interval has to be irregular.
Unfortunately Highcharts doesn't provide a property to do that automatically - some coding and restructuring the data is required:
All the points have specified x position (integer value)
xAxis.grouping is disabled and xAxis.pointRangeis 1
Following code is used to define and position the labels:
events: {
render: function() {
var xAxis = this.xAxis[0];
for (var i = 0; i < xAxis.tickPositions.length; i++) {
var tickPosition = xAxis.tickPositions[i],
tick = xAxis.ticks[tickPosition],
nextTickPosition,
nextTick;
if (!tick.isLast) {
nextTickPosition = xAxis.tickPositions[i + 1];
nextTick = xAxis.ticks[nextTickPosition];
tick.label.attr({
y: (new Number(tick.mark.d.split(' ')[2]) + new Number(nextTick.mark.d.split(' ')[2])) / 2 + 3
});
}
}
}
}
(...)
xAxis: {
tickPositions: [-0.5, 6.5, 7.5],
showLastLabel: false,
labels: {
formatter: function() {
switch (this.pos) {
case -0.5:
return 'Bananas';
case 6.5:
return 'Apples';
}
}
}
}
Live demo: http://jsfiddle.net/BlackLabel/2Lcs5up5/

Data changing with Highcharts point.update

Edit: Here is a Fiddle - slightly different (simplified) code to examples below but same problem.
I have a simple Highcharts bar chart showing two series of data for 2011 (truncated):
var dataset = {};
dataset.attchange2011 = [
{y: -8.5},
{y: -8.3}
];
dataset.revchange2011 = [
{y: -14.9},
{y: -10.7}
];
This is displaying properly in the graph on load:
...
series: [{
name: 'Change in Revenue',
data: dataset['revchange2012']
},{
name: 'Change in Attendance',
data: dataset['attchange2012']
}]
...
I have a second set of data for 2012:
dataset.attchange2012 = [
{y: 1.2 },
{y: 14.1}
];
dataset.revchange2012 = [
{y: 11.5},
{y: 37.5}
];
And a simple function to switch between the years by getting the data-year value from a link that's clicked, loop through that year's data and update the series points values, followed by a redraw:
...
year = $(this).data('year').toString();
$.each(chart.series[0].data, function (i, point) {
point.update(dataset['revchange'+year][i], false);
});
$.each(chart.series[1].data, function (i, point) {
point.update(dataset['attchange'+year][i], false);
});
...
The first time the 2011 link is clicked, the data updates correctly. Trying to switch back to 2012 doesn't work.
When looking at each data set at various stages by console.log(dataset), it appears that it is correctly set on page load:
dataset
Object
attchange2011: Array[8]
0: Object
y: -8.5
...
attchange2012: Array[8]
0: Object
y: 1.2
But changes when the link is clicked - 2011 values are copied to the 2012 data set:
dataset
Object
attchange2011: Array[8]
0: Object
y: -8.5
...
attchange2012: Array[8]
0: Object
y: -8.5
I can't figure out where or why it would be doing that. Any ideas? I am not completely against rewriting everything from scratch if needed.
It's caused by Highcharts. Variables are overwritten when updating points. Instead, use copy of that objects: http://jsfiddle.net/RF7aW/7/
series: [$.extend(true, {}, data2013[0]), $.extend(true, {}, data2013[1])],
If not against rewriting, I suggest a much cleaner approach which would be this:
Define an actual function, function makeChart(data) and initialize it like you do now, giving it the 2012 data. On click of 2012 or 2011 or whatever other button, simply call makeChart(otherData). This extracts the whole updating issue which, by the way, you don't need to iterate through every single point, you can just update the data series entirely with series.update (which I believe redraws anyways).
EDIT:
If not redrawing, try using simple buttons and using series.setData() instead:
JSfiddle

Limit labels number on Chart.js line chart

I want to display all of the points on my chart from the data I get, but I don't want to display all the labels for them, because then the chart is not very readable. I was looking for it in the docs, but couldn't find any parameter that would limit this.
I don't want to take only three labels for example, because then the chart is also limited to three points. Is it possible?
I have something like that right now:
If I could just leave every third-fourth label, it would be great. But I found absolutely nothing about labels options.
Try adding the options.scales.xAxes.ticks.maxTicksLimit option:
xAxes: [{
type: 'time',
ticks: {
autoSkip: true,
maxTicksLimit: 20
}
}]
For concreteness, let's say your original list of labels looks like:
["0", "1", "2", "3", "4", "5", "6", "7", "8"]
If you only want to display every 4th label, filter your list of labels so that every 4th label is filled in, and all others are the empty string (e.g. ["0", "", "", "", "4", "", "", "", "8"]).
For anyone looking to achieve this on Chart JS V2 the following will work:
var options = {
scales: {
xAxes: [{
afterTickToLabelConversion: function(data){
var xLabels = data.ticks;
xLabels.forEach(function (labels, i) {
if (i % 2 == 1){
xLabels[i] = '';
}
});
}
}]
}
}
Then pass the options variable as usual into a:
myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});`
UPDATE:
I'v updated my fork with the latest pull (as of Jan 27, 2014) from NNick's Chart.js master branch.
https://github.com/hay-wire/Chart.js/tree/showXLabels
ORIGINAL ANSWER:
For those still facing this issue, I forked Chart.js a while back to solve the same problem. You can check it out on:
https://github.com/hay-wire/Chart.js/tree/skip-xlabels => Older branch! Check showXLabels branch for latest pull.
How to use:
Applicable to bar chart and line chart.
User can now pass a { showXLabels: 10 } to display only 10 labels (actual displayed labels count might be a bit different depending on the number of total labels present on x axis, but it will still remain close to 10 however)
Helps a lot when there is a very large amount of data. Earlier, the graph used to look devastated due to x axis labels drawn over each other in the cramped space. With showXLabels, user now has the control to reduce the number of labels to whatever number of labels fit good into the space available to him.
See the attached images for a comparison.
Without showXLabels option:
With { showXLabels: 10 } passed into option:
Here's some discussion on it:
https://github.com/nnnick/Chart.js/pull/521#issuecomment-60469304
For Chart.js 3.3.2, you can use #Nikita Ag's approach with a few changes. You can check the documentation. Put ticks in xAxis in scales. Example:
...
options: {
scales: {
xAxis: {
ticks: {
maxTicksLimit: 10
}
}
}
}
...
for axis rotation
use this:
scales: {
xAxes: [
{
// aqui controlas la cantidad de elementos en el eje horizontal con autoSkip
ticks: {
autoSkip: true,
maxRotation: 0,
minRotation: 0
}
}
]
}
In Chart.js 3.2.0:
options: {
scales: {
x: {
ticks: {
maxTicksLimit: 10
}
}
}
}
According to the chart.js github issue #12. Current solutions include:
Use 2.0 alpha (not production)
Hide x-axis at all when it becames too crowd (cannot accept at all)
manually control label skip of x-axis (not in responsive page)
However, after a few minutes, I thinks there's a better solution.
The following snippet will hide labels automatically. By modify xLabels with empty string before invoke draw() and restore them after then. Even more, re-rotating x labels can be applied as there's more space after hiding.
var axisFixedDrawFn = function() {
var self = this
var widthPerXLabel = (self.width - self.xScalePaddingLeft - self.xScalePaddingRight) / self.xLabels.length
var xLabelPerFontSize = self.fontSize / widthPerXLabel
var xLabelStep = Math.ceil(xLabelPerFontSize)
var xLabelRotationOld = null
var xLabelsOld = null
if (xLabelStep > 1) {
var widthPerSkipedXLabel = (self.width - self.xScalePaddingLeft - self.xScalePaddingRight) / (self.xLabels.length / xLabelStep)
xLabelRotationOld = self.xLabelRotation
xLabelsOld = clone(self.xLabels)
self.xLabelRotation = Math.asin(self.fontSize / widthPerSkipedXLabel) / Math.PI * 180
for (var i = 0; i < self.xLabels.length; ++i) {
if (i % xLabelStep != 0) {
self.xLabels[i] = ''
}
}
}
Chart.Scale.prototype.draw.apply(self, arguments);
if (xLabelRotationOld != null) {
self.xLabelRotation = xLabelRotationOld
}
if (xLabelsOld != null) {
self.xLabels = xLabelsOld
}
};
Chart.types.Bar.extend({
name : "AxisFixedBar",
initialize : function(data) {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
this.scale.draw = axisFixedDrawFn;
}
});
Chart.types.Line.extend({
name : "AxisFixedLine",
initialize : function(data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
this.scale.draw = axisFixedDrawFn;
}
});
Please notice that clone is an external dependency.
i had a similar type of issue, and was given a nice solution to my specific issue show label in tooltip but not in x axis for chartjs line chart. See if this helps you
you can limit at as
scales: {
x: {
ticks: {
// For a category axis, the val is the index so the lookup via getLabelForValue is needed
callback: function(val, index) {
// Hide the label of every 2nd dataset
return index % 5 === 0 ? this.getLabelForValue(val) : '';
},
}
}
}
this will skip 4 labels and set the 5th one only.
you can use the following code:
xAxes: [{
ticks: {
autoSkip: true,
maxRotation: 90
}
}]
You may well not need anything with this new built-in feature.
A built-in label auto-skip feature detects would-be overlapping ticks and labels and removes every nth label to keep things displaying normally. https://www.chartjs.org/docs/latest/axes/
To set a custom number of ticks regardless of your chartsjs version:
yAxes: [{
ticks: {
stepSize: Math.round((Math.max.apply(Math, myListOfyValues) / 10)/5)*5,
beginAtZero: true,
precision: 0
}
}]
10 = the number of ticks
5 = rounds tick values to the nearest 5. All your y values will have the same step size.
Similar will work for xAxes too.
This answer works like a charm.
If you are wondering about the clone function, try this one:
var clone = function(el){ return el.slice(0); }
In the Chart.js file, you should find (on line 884 for me)
var Line = function(...
...
function drawScale(){
...
ctx.fillText(data.labels[i], 0,0);
...
If you just wrap that one line call to fillText with if ( i % config.xFreq === 0){ ... }
and then in chart.Line.defaults add something line xFreq : 1 you should be able to start using xFreq in your options when you call new Chart(ctx).Line(data, options).
Mind you this is pretty hacky.

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