I have some plotLines and I just need to print labels corresponding to those plotLines on my xAxis.
My data is a random value around 100 (yAxis) and dates that increments by 10 days (xAxis).
var getDaysArray = function(start, end) {
for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 10)) {
arr.push(new Date(dt));
}
return arr;
};
function generateDataPoints(noOfDps) {
var yVal = 100;
var dps = [];
var xDate = getDaysArray(new Date("2006-01-01"), new Date("2019-12-30"));
for (var i = 0; i < xDate.length; i++) {
yVal = yVal + Math.round(5 + Math.random() * (-5 - 5));
dps.push({ x: xDate[i], y: yVal });
}
return dps;
}
let dataPoints = generateDataPoints(100);
There is also a function that gets the min, max, first and last values of y and returns an array of markers. Those are the points where I have plotLines.
function setHighestLowest(dtPoints) {
let highestIndex = -1;
let minimumIndex = -1;
let highestValue = 0;
let lowestValue = 0;
for (let i = 0; i < dtPoints.length; i++) {
let obj = dtPoints[i];
if (obj.y > highestValue) {
highestIndex = i;
highestValue = obj.y;
}
if (obj.y < lowestValue || i === 0) {
minimumIndex = i;
lowestValue = obj.y;
}
}
dtPoints[0].indexLabel = dtPoints[0].y.toString();
dtPoints[dtPoints.length - 1].indexLabel = dtPoints[
dtPoints.length - 1
].y.toString();
if (highestIndex > -1) {
dtPoints[highestIndex].indexLabel = dtPoints[highestIndex].y.toString();
}
if (minimumIndex > -1) {
dtPoints[minimumIndex].indexLabel = dtPoints[minimumIndex].y.toString();
}
//returns -> [max[0], min[1], first[2], last[3]]
let dateMarker = [
dtPoints[highestIndex].x,
dtPoints[minimumIndex].x,
dtPoints[1].x,
dtPoints[dtPoints.length - 1].x
];
//console.log(dateMarker);
return dateMarker;
}
My approach is to define labels.formatter functions for the xAxis.
First issue I found was the increment steps, I tried xAxis.labels.step but it didn't work, than I found xAxis.tickIntervals it seemed to work at first, the only problem was that to prevent labels from being printed outside of xAxis area the formatter function value started from a previous point from my dataset, there was some kind of offset, formatter function increment would never fit my data (offset problem). To solve this offset problem I tried the xAxis.tickPositions and called my markers array, from that point I was able to acces the points on formatter function, the only problem is that it returns nothing, I get inside the if loop that does the checking but nothing is printed on xAxis.labels.
The final result I want in my plot is something like that:
This is my code:
What do you think about use the plotLines.label feature to render those labels? I think that it will be easier to implement this logic there.
Demo: https://codesandbox.io/s/highcharts-react-xaxis-label-formatter-8xdcg
API: https://api.highcharts.com/highcharts/xAxis.plotLines.label
Related
I'm trying to identify if a value is a Perfect Square and if that's the case, I want to push it into an array. I know that there is a built-in function that allows for it but I want to create an algorithm that does it. :)
Input: num = 16
Output: [4]
Example 2:
Input: num = 25
Output: [5]
Example 2:
Input: num = 14
Output: []
var isPerfectSquare = function(value) {
var perfectSquareVal = []
var highestValue = value;
var lowestValue = 0;
while (lowestValue < highestValue) {
var midpoint = 1 + Math.floor((highestValue + lowestValue)/2);
if (midpoint * midpoint === value) {
perfectSquareVal.push(midpoint);
} else if (midpoint * midpoint > value) {
highestValue = midpoint;
} else if (midpoint * midpoint < value) {
lowestValue = midpoint;
}
}
console.log(perfectSquareVal);
};
isPerfectSquare(16);
That seems really complicated to check if a number is a square, you could simply check if the square root is an Integer:
var isPerfectSquare = function(value) {
return Number.isInteger(Math.sqrt(value));
}
And if the function returns true, then push to array.
You could change the algorithm a bit by
taking the arthmetic mean with a flored value,
return if the product is found (why an array for the result?),
check only the greater oroduct because the smaller one is included in the check for equalness,
use decremented/incremented values, becaus the actual value is wrong,
keep a pure function, take ouput to the outside.
var isPerfectSquare = function (value) {
var highestValue = value,
lowestValue = 0;
while (lowestValue < highestValue) {
let midpoint = Math.floor((highestValue + lowestValue) / 2),
product = midpoint * midpoint;
if (product === value) return midpoint;
if (product > value) highestValue = midpoint - 1;
else lowestValue = midpoint + 1;
}
};
console.log(isPerfectSquare(25));
console.log(isPerfectSquare(250));
So right now, I'm trying to implement a search bar function into my d3.js plot. Right now it doesn't do anything, but that's not the issue at the moment. The problem is that when I type/delete something from the bar, there's visible lag/choppiness in the characters appearing/disappearing. I believe the issue is stemming from my plot. I have 140+ dots moving around the screen, and their position is being interpolated. So from the beginning to the end of the transition, my code has to compute 140 positions thousands of times over.
I've looked into trying to reduce the cardinality of the d3.interpolateNumber function, but it appears that there isn't a third argument to change the number of terms like in a linspace command. Right now I have an array of 1000 numbers for my function to run through, but I don't know how to pass the array to my other functions.
Below are the pertinent functions for this issue. The commented line in tweenPatch is the original code I had that made my code run, but gave my plot computational issues. Variables arr, curr, and step were my attempt to fix the situation, but I haven't been able to figure out how to pass the array into displayPatch().
function tweenPatch() {
var patch = d3.interpolateNumber(1, 26);
var arr = [];
var curr = 1;
var step = (26 - 1) / (1000 - 1);
for (var i = 0; i < 1000; i++) {
arr.push(curr + (step * i));
}
return arr.forEach(function(d) {
console.log(arr[d]);
displayPatch(arr[d]);
});
//return function(t) { displayPatch(t); };
}
function displayPatch(patch) {
dots.data(interpolateData(patch), function(d) { return d.name; }).call(position).sort(order);
var inter = Math.floor(patch);
var seas = 8;
var patc = 1;
if (inter > 24) {
seas = 9;
patc = inter - 24;
} else {
patc = inter;
}
label.text("Patch " + seas + "." + patc);
}
function interpolateValues(values, number) {
old = Math.floor(number);
upd = Math.ceil(number);
var old_data = values.filter(function(d) {return d.internal == old;});
var new_data = values.filter(function(d) {return d.internal == upd;});
var oobj = old_data[0];
var nobj = new_data[0];
var onum = oobj[Object.keys(oobj)[4]];
var nnum = nobj[Object.keys(nobj)[4]];
var difint = number - old;
var difdis = 0;
var newnum = nnum;
if (nnum > onum) {
difdis = nnum - onum;
newnum = ((difint) * difdis) + onum;
} else if (onum > nnum) {
difdis = onum - nnum;
newnum = onum - ((difint) * difdis);
}
return newnum;
}
I believe switching my SVG to a canvas may help things, but since I have no knowledge of canvas I'd rather leave that as a last resort.
So I am looking to create look up tables. However I am running into a problem with integer ranges instead of just 1, 2, 3, etc. Here is what I have:
var ancient = 1;
var legendary = 19;
var epic = 251;
var rare = 1000;
var uncommon = 25000;
var common = 74629;
var poolTotal = ancient + legendary + epic + rare + uncommon + common;
var pool = general.rand(1, poolTotal);
var lootPool = {
1: function () {
return console.log("Ancient");
},
2-19: function () {
}
};
Of course I know 2-19 isn't going to work, but I've tried other things like [2-19] etc etc.
Okay, so more information:
When I call: lootPool[pool](); It will select a integer between 1 and poolTotal Depending on if it is 1 it will log it in the console as ancient. If it hits in the range of 2 through 19 it would be legendary. So on and so forth following my numbers.
EDIT: I am well aware I can easily do this with a switch, but I would like to try it this way.
Rather than making a huge lookup table (which is quite possible, but very inelegant), I'd suggest making a (small) object, choosing a random number, and then finding the first entry in the object whose value is greater than the random number:
// baseLootWeight: weights are proportional to each other
const baseLootWeight = {
ancient: 1,
legendary: 19,
epic: 251,
rare: 1000,
uncommon: 25000,
common: 74629,
};
let totalWeightSoFar = 0;
// lootWeight: weights are proportional to the total weight
const lootWeight = Object.entries(baseLootWeight).map(([rarity, weight]) => {
totalWeightSoFar += weight;
return { rarity, weight: totalWeightSoFar };
});
console.log(lootWeight);
const randomType = () => {
const rand = Math.floor(Math.random() * totalWeightSoFar);
return lootWeight
.find(({ rarity, weight }) => weight >= rand)
.rarity;
};
for (let i = 0; i < 10; i++) console.log(randomType());
Its not a lookup, but this might help you.
let loots = {
"Ancient": 1,
"Epic": 251,
"Legendary": 19
};
//We need loots sorted by value of lootType
function prepareSteps(loots) {
let steps = Object.entries(loots).map((val) => {return {"lootType": val[0], "lootVal": val[1]}});
steps.sort((a, b) => a.lootVal > b.lootVal);
return steps;
}
function getMyLoot(steps, val) {
let myLootRange;
for (var i = 0; i < steps.length; i++) {
if((i === 0 && val < steps[0].lootVal) || val === steps[i].lootVal) {
myLootRange = steps[i];
break;
}
else if( i + 1 < steps.length && val > steps[i].lootVal && val < steps[i + 1].lootVal) {
myLootRange = steps[i + 1];
break;
}
}
myLootRange && myLootRange['lootType'] ? console.log(myLootRange['lootType']) : console.log('Off Upper Limit!');
}
let steps = prepareSteps(loots);
let pool = 0;
getMyLoot(steps, pool);
Does anyone know how to disable a stream after drawing?
I'm looking to modify the active streams after the page has loaded, and the user has clicked on a button in a different part of the page.
I've been working on code to simulate a click event after it determines it's state, but that seems kind of clunky and slow.
EDIT:
As requested, here's an example of an NVD3 chart with multiple streams (data series found in the legend).
After chart render, I am looking for a function that can enable / disable multiple streams (data 0, data 1, etc. on the example) in a single call.
I was working on something that dispatches click events to the labels, but thought there must be a better way.
<div id="chart">
<svg></svg>
</div>
var data = function() {
return stream_layers(4,10+Math.random()*10,.1).map(function(data, i) {
return {
key: 'Data ' + i,
values: data
};
});
}
function stream_layers(n, m, o) {
if (arguments.length < 3) o = 0;
function bump(a) {
var x = 1 / (.1 + Math.random()),
y = 2 * Math.random() - .5,
z = 10 / (.1 + Math.random());
for (var i = 0; i < m; i++) {
var w = (i / m - y) * z;
a[i] += x * Math.exp(-w * w);
}
}
return d3.range(n).map(function () {
var a = [],
i;
for (i = 0; i < m; i++) a[i] = o + o * Math.random();
for (i = 0; i < 5; i++) bump(a);
return a.map(stream_index);
});
}
function stream_index(d, i) {
return {
x: i,
y: Math.max(0, d)
};
}
nv.addGraph(function () {
var chart = nv.models.multiBarChart();
chart.multibar.stacked(false);
chart.showControls(false);
chart.showLegend(true);
chart.reduceXTicks(false);
d3.select('#chart svg')
.datum(data())
.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
Found my answer..
The following works
chartData[i].disabled = true; // chartData = original data object fed to NVD3 chart
chartData[i].userDisabled = true;
chart.update(); // chart = a reference to your NVD3 chart instance.
I have a database that has got a month full of datasets in 10min intervals. (So a dataset for every 10min)
Now I want to show that data on three graphs: last 24 hours, last 7 days and last 30 days.
The data looks like this:
{ "data" : 278, "date" : ISODate("2016-08-31T01:51:05.315Z") }
{ "data" : 627, "date" : ISODate("2016-08-31T01:51:06.361Z") }
{ "data" : 146, "date" : ISODate("2016-08-31T01:51:07.938Z") }
// etc
For the 24h graph I simply output the data for the last 24h, that's easy.
For the other graphs I thin the data:
const data = {}; //data from database
let newData = [];
const interval = 7; //for 7 days the interval is 7, for 30 days it's 30
for( let i = 0; i < data.length; i += interval ) {
newData.push( data[ i ] );
};
This works fine but extreme events where data is 0 or differs greatly from the other values average, can be lost depending on what time you search the data. Not thinning out the data however will result in a large sum of data points that are sent over the pipe and have to be processed on the front end. I'd like to avoid that.
Now to my question
How can I reduce the data for a 7 day period while keeping extremes in it? What's the most efficient way here?
Additions:
In essence I think I'm trying to simplify a graph to reduce points but keep the overall shape. (If you look at it from a pure image perspective)
Something like an implementation of Douglas–Peucker algorithm in node?
As you mention in the comments, the Ramer-Douglas-Peucker (RDP) algorithm is used to process data points in 2D figures but you want to use it for graph data where X values are fixed. I modified this Javascript implementation of the algorithm provided by M Oehm to consider only the vertical (Y) distance in the calculations.
On the other hand, data smoothing is often suggested to reduce the number of data points in a graph (see this post by csgillespie).
In order to compare the two methods, I made a small test program. The Reset button creates new test data. An algorithm can be selected and applied to obtain a reduced number of points, separated by the specified interval. In the case of the RDP algorithm however, the resulting points are not evenly spaced. To get the same number of points as for the specified interval, I run the calculations iteratively, adjusting the espilon value each time until the correct number of points is reached.
From my tests, the RDP algorithm gives much better results. The only downside is that the spacing between points varies. I don't think that this can be avoided, given that we want to keep the extreme points which are not evenly distributed in the original data.
Here is the code snippet, which is better seen in Full Page mode:
var svgns = 'http://www.w3.org/2000/svg';
var graph = document.getElementById('graph1');
var grpRawData = document.getElementById('grpRawData');
var grpCalculatedData = document.getElementById('grpCalculatedData');
var btnReset = document.getElementById('btnReset');
var cmbMethod = document.getElementById('cmbMethod');
var btnAddCalculated = document.getElementById('btnAddCalculated');
var btnClearCalculated = document.getElementById('btnClearCalculated');
var data = [];
var calculatedCount = 0;
var colors = ['black', 'red', 'green', 'blue', 'orange', 'purple'];
var getPeriod = function () {
return parseInt(document.getElementById('txtPeriod').value, 10);
};
var clearGroup = function (grp) {
while (grp.lastChild) {
grp.removeChild(grp.lastChild);
}
};
var showPoints = function (grp, pts, markerSize, color) {
var i, point;
for (i = 0; i < pts.length; i++) {
point = pts[i];
var marker = document.createElementNS(svgns, 'circle');
marker.setAttributeNS(null, 'cx', point.x);
marker.setAttributeNS(null, 'cy', point.y);
marker.setAttributeNS(null, 'r', markerSize);
marker.setAttributeNS(null, 'fill', color);
grp.appendChild(marker);
}
};
// Create and display test data
var showRawData = function () {
var i, x, y;
var r = 0;
data = [];
for (i = 1; i < 500; i++) {
x = i;
r += 15.0 * (Math.random() * Math.random() - 0.25);
y = 150 + 30 * Math.sin(x / 200) * Math.sin((x - 37) / 61) + 2 * Math.sin((x - 7) / 11) + r;
data.push({ x: x, y: y });
}
showPoints(grpRawData, data, 1, '#888');
};
// Gaussian kernel smoother
var createGaussianKernelData = function () {
var i, x, y;
var r = 0;
var result = [];
var period = getPeriod();
for (i = Math.floor(period / 2) ; i < data.length; i += period) {
x = data[i].x;
y = gaussianKernel(i);
result.push({ x: x, y: y });
}
return result;
};
var gaussianKernel = function (index) {
var halfRange = Math.floor(getPeriod() / 2);
var distance, factor;
var totalValue = 0;
var totalFactor = 0;
for (i = index - halfRange; i <= index + halfRange; i++) {
if (0 <= i && i < data.length) {
distance = Math.abs(i - index);
factor = Math.exp(-Math.pow(distance, 2));
totalFactor += factor;
totalValue += data[i].y * factor;
}
}
return totalValue / totalFactor;
};
// Ramer-Douglas-Peucker algorithm
var ramerDouglasPeuckerRecursive = function (pts, first, last, eps) {
if (first >= last - 1) {
return [pts[first]];
}
var slope = (pts[last].y - pts[first].y) / (pts[last].x - pts[first].x);
var x0 = pts[first].x;
var y0 = pts[first].y;
var iMax = first;
var max = -1;
var p, dy;
// Calculate vertical distance
for (var i = first + 1; i < last; i++) {
p = pts[i];
y = y0 + slope * (p.x - x0);
dy = Math.abs(p.y - y);
if (dy > max) {
max = dy;
iMax = i;
}
}
if (max < eps) {
return [pts[first]];
}
var p1 = ramerDouglasPeuckerRecursive(pts, first, iMax, eps);
var p2 = ramerDouglasPeuckerRecursive(pts, iMax, last, eps);
return p1.concat(p2);
}
var internalRamerDouglasPeucker = function (pts, eps) {
var p = ramerDouglasPeuckerRecursive(data, 0, pts.length - 1, eps);
return p.concat([pts[pts.length - 1]]);
}
var createRamerDouglasPeuckerData = function () {
var finalPointCount = Math.round(data.length / getPeriod());
var epsilon = getPeriod();
var pts = internalRamerDouglasPeucker(data, epsilon);
var iteration = 0;
// Iterate until the correct number of points is obtained
while (pts.length != finalPointCount && iteration++ < 20) {
epsilon *= Math.sqrt(pts.length / finalPointCount);
pts = internalRamerDouglasPeucker(data, epsilon);
}
return pts;
};
// Event handlers
btnReset.addEventListener('click', function () {
calculatedCount = 0;
clearGroup(grpRawData);
clearGroup(grpCalculatedData);
showRawData();
});
btnClearCalculated.addEventListener('click', function () {
calculatedCount = 0;
clearGroup(grpCalculatedData);
});
btnAddCalculated.addEventListener('click', function () {
switch (cmbMethod.value) {
case "Gaussian":
showPoints(grpCalculatedData, createGaussianKernelData(), 2, colors[calculatedCount++]);
break;
case "RDP":
showPoints(grpCalculatedData, createRamerDouglasPeuckerData(), 2, colors[calculatedCount++]);
return;
}
});
showRawData();
div
{
margin-bottom: 6px;
}
<div>
<button id="btnReset">Reset</button>
<select id="cmbMethod">
<option value="RDP">Ramer-Douglas-Peucker</option>
<option value="Gaussian">Gaussian kernel</option>
</select>
<label for="txtPeriod">Interval: </label>
<input id="txtPeriod" type="text" style="width: 36px;" value="7" />
</div>
<div>
<button id="btnAddCalculated">Add calculated points</button>
<button id="btnClearCalculated">Clear calculated points</button>
</div>
<svg id="svg1" width="765" height="450" viewBox="0 0 510 300">
<g id="graph1" transform="translate(0,300) scale(1,-1)">
<rect width="500" height="300" stroke="black" fill="#eee"></rect>
<g id="grpRawData"></g>
<g id="grpCalculatedData"></g>
</g>
</svg>