Efficient multi-chart drag selection for highcharts - javascript

I've used Highcharts documentation to enable a drag selection for a chart. I'm trying to expand this so that whatever points I've selected on my first chart, will also be selected on the other charts on the page (the x axis matches).
I've figured out a method to do this, & it works well for 2 or 3 highcharts on a page, but it gets some severe lag when i select many points (each chart is about 1500 points total) with 4 or more highcharts.
It could be because I use a nested for loop, but I was wondering if anyone had any tips for improving the efficiency of this code (or if this is even the issue). The first function is the one provided in the Highcharts documentation; the second function (updateCharts()) is the one I did.
I've never used highcharts, or programmed much in javascript before, so I'm still a bit unfamiliar with how all this works.
function selectPointsByDrag(e) {
// Select points
Highcharts.each(this.series, function (series) {
Highcharts.each(series.points, function (point) {
if (point.x >= e.xAxis[0].min && point.x <= e.xAxis[0].max &&
point.y >= e.yAxis[0].min && point.y <= e.yAxis[0].max) {
point.select(true, true);
}
});
});
// Fire a custom event
Highcharts.fireEvent(this, 'selectedpoints', { points: this.getSelectedPoints() });
updateCharts(this);
return false; // Don't zoom
};
function updateCharts(curr_chart){
var count;
var counter;
var allChartArray = [chart, chart1, chart2, chart3];
var indexOfCurrentChart = allChartArray.indexOf(curr_chart);
if (indexOfCurrentChart > -1) {
allChartArray.splice(indexOfCurrentChart, 1);
};
bla = curr_chart.getSelectedPoints();
for(count = 0; count < allChartArray.length; count++){
for(counter = 0; counter < bla.length; counter++){
allChartArray[count].series[0].data[bla[counter].index].select(true, true)
};
};
};

Related

Why is my maze generator not detecting if a cell has been visited in p5.js?

I am trying to make a maze generator, and almost everything is working so far. I have been able to set my position to a random pos, and then I repeat the standard() function. In the function, I add pos to posList, and then I choose a random direction. Next, I check if the cell has been visited by running through all of the posList vectors in reverse. I haven't executed the code that backtracks yet. If visited = false then I move to the square and execute the yet-to-be-made path() function. However, for some reason, the mover just doesn't detect if a cell has been visited or not. I am using p5.js. What am I doing wrong?
var posList = [];
var pos;
var tempo;
var boole = false;
var direc;
var mka = 0;
function setup() {
createCanvas(400, 400);
//Set up position
pos = createVector(floor(random(3)), floor(random(3)));
frameRate(1)
}
//Choose a direction
function direct(dire) {
if(dire === 0) {
return(createVector(0, -1));
} else if(dire === 1) {
return(createVector(1, 0));
} else if(dire === 2) {
return(createVector(0, 1));
} else {
return(createVector(-1, 0));
}
}
/foLo stands fo forLoop
function foLo() {
//If we have checked less than three directions and know there is a possibility for moving
if(mka < 4) {
//tempoRARY, this is what we use to see if the cell has been visited
tempo = createVector(pos.x + direct(direc).x, pos.y + direct(direc).y);
//Go through posList backwards
for(var i = posList.length - 1; i >= 0; i --) {
//If the cell has been visited or the cell is off of the screen
if(tempo === posList[i]) {
//Change the direction
direc ++;
//Roll over direction value
if(direc === 4) {
direc = 0;
}
//Re-execute on next frame
foLo();
//The cell has been visited
boole = false;
//Debugging
console.log(direc)
mka++;
} else if(tempo.x < 0 || tempo.x > 2 || tempo.y < 0 || tempo.y > 2) {
direc ++;
if(direc === 4) {
direc = 0;
}
foLo();
boole = false;
console.log(direc)
mka++;
}
}
//If it wasn't visited (Happens every time for some reason)
if(boole === true) {
//position is now the temporary value
pos = tempo;
console.log("works")
mka = 0;
}
}
}
function standard() {
//Add pos to posList
posList.push(pos);
//Random direction
direc = floor(random(4));
//Convert to vector
direct(direc);
foLo();
//Tracks pos
fill(255, 255, 0);
rect(pos.x*100+50, pos.y*100+50, 50, 50)
}
function draw() {
background(255);
fill(0);
noStroke();
//draw grid
for(var i = 0; i < 4; i ++) {
rect(i*100,0,50,350);
rect(0, i*100, 350, 50);
}
standard();
boole = true;
console.log(pos)
console.log(posList);
}
Your issue is on the line where you compare two vectors if(tempo === posList[i]) {: This will never be true.
You can verify that with the following code (in setup() for example):
const v1 = new p5.Vector(1, 0);
const v2 = new p5.Vector(1, 0);
const v3 = new p5.Vector(1, 1);
console.log(v1 === v2) // false
console.log(v1 === v3) // false
This is because despite having the same value v1 and v2 are referencing two different objects.
What you could do is using the p5.Vector.equals function. The doc has the following example:
let v1 = createVector(10.0, 20.0, 30.0);
let v2 = createVector(10.0, 20.0, 30.0);
let v3 = createVector(0.0, 0.0, 0.0);
print(v1.equals(v2)); // true
print(v1.equals(v3)); // false
This might not give you a working algorithm because I suspect you have other logical errors (but I could be wrong or you will debug them later on) but at least this part of the code will do what you expect.
Another solution is to use a Set instead of your list of positions. The cons of this solution is that you will have to adapt your code to handle the "out of grid" position situation. However when you want to keep track of visited items a Set is usually a great solution because the access time is constant. That this means is that to define is a position has already been visited it will always take the same time (you'll do something like visitedSet.has(positionToCheck), whereas with your solution where you iterate through a list the more cells you have visited to longer it will take to check if the cell is in the list.
The Set solution will require that you transform your vectors before adding them to the set though sine, has I explained before you cannot simply compare vectors. So you could check for their string representation with something like this:
const visitedCells = new Set();
const vectorToString = (v) => `${v.x},{$v.y}` // function to get the vector representation
// ...
visitedCells.add(vectorToString(oneCell)); // Mark the cell as visited
visited = visitedCells.has(vectorToString(anotherCell))
Also has a general advice you should pay attention to your variables and functions name. For example
// foLo stands fo forLoop
function foLo() {
is a big smell: Your function name should be descriptive, when you see your function call foLo(); having to find the comment next to the function declaration makes the code less readable. You could call it generateMaze() and this way you'll know what it's doing without having to look at the function code.
Same for
//tempoRARY, this is what we use to see if the cell has been visited
tempo = createVector(pos.x + direct(direc).x, pos.y + direct(direc).y);
You could simply rename tempo to cellToVisit for example.
Or boole: naming a boolean boole doesn't convey a lot of information.
That could look like some minor details when you just wrote the code but when your code will be several hundred lines or when you read it again after taking several days of break, you'll thank past you for taking care of that.

flot multiple line graph animation

I have multiple series on a graph and would like to animate them but it is not working. I am using flot and animator plugin.
https://jsfiddle.net/shorif2000/L0vtrgc2/
var datasets = [{"label":"IT","curvedLines":{"apply":true},"animator":{"start":0,"steps":7,"duration":3000,"direction":"right"},"idx":0,"data":[{"0":1433156400000,"1":"095.07"},{"0":1435748400000,"1":"097.80"},{"0":1438426800000,"1":"096.72"},{"0":1441105200000,"1":"097.62"},{"0":1443697200000,"1":"097.68"},{"0":1446379200000,"1":"098.49"},{"0":1448971200000,"1":"098.59"},{"0":1451649600000,"1":"098.69"}]},{"label":"Network","curvedLines":{"apply":true},"animator":{"start":0,"steps":7,"duration":3000,"direction":"right"},"idx":1,"data":[{"0":1433156400000,"1":"095.07"},{"0":1435748400000,"1":"097.80"},{"0":1438426800000,"1":"096.72"},{"0":1441105200000,"1":"097.62"},{"0":1443697200000,"1":"097.68"},{"0":1446379200000,"1":"098.49"},{"0":1448971200000,"1":"098.59"},{"0":1451649600000,"1":"098.69"}]},{"label":"Success Rate","curvedLines":{"apply":true},"animator":{"start":0,"steps":7,"duration":3000,"direction":"right"},"idx":2,"data":[[1433156400000,98.58],[1433156400000,null],[1433156400000,95.18],[1433156400000,null],[1435748400000,null],[1438426800000,null],[1441105200000,null],[1443697200000,null],[1446379200000,null],[1448971200000,null],[1451649600000,null]]}];
var options = {"series":{"lines":{"show":true},"curvedLines":{"active":true}},"xaxis":{"mode":"time","tickSize":[1,"month"],"timeformat":"%b %y"},"grid":{"clickable":true,"hoverable":true},"legend":{"noColumns":3,"show":true}};
$.plotAnimator($('#CAGraph'), datasets, options);
Problem I have is when I add curved lines it does not work. https://github.com/MichaelZinsmaier/CurvedLines
Without curvedLines plugin (like in the fiddle in your question):
1) If you have multiple data series and use animator, it will only animate the last series. All other series are drawn instantly. (You can see this in your fiddle when you comment out the third data series.)
2) Your last data series has only two points at the same date, so there is nothing to animate (this leads also to problems with the curvedLines plugin for this series).
To animate multiple data series one by one see this answer to another question.
With curvedLines plugin:
3) The curvedLines plugin doesn't work together with the animator plugin (probably because the animator plugin generates a new partial data series for each step). But we can work around this issue with these steps:
a) plot a curvedLines chart without animator,
b) read the data points from this chart and replace the original data,
c) change the options (deactivate curvedLines since the new data is already curved and adjust the step count to the new data),
d) plot the animated chart with the new data.
See this fiddle for a working example with one data series. Relevant code:
var plot = $.plot($('#CAGraph'), datasets, options);
var newData = plot.getData()[0].datapoints.points;
datasets[0].data = [];
for (var i = 0; i < newData.length; i = i+2) {
datasets[0].data.push([newData[i], newData[i+1]]);
}
datasets[0].animator.steps = (newData.length / 2) - 1;
options.series.curvedLines.active = false;
var ani = $.plotAnimator($('#CAGraph'), datasets, options);
Full solution:
Combining the two parts above we get a fiddle which animates two curved lines one by one (the third data series is left out because of the issues mentioned under 2)). Relevant code:
var chartcount = datasets.length;
var chartsdone = 0;
var plot = $.plot($('#CAGraph'), datasets, options);
for (var i = 0; i < chartcount; i++) {
var newData = plot.getData()[i].datapoints.points;
datasets[i].data = [];
for (var j = 0; j < newData.length; j = j + 2) {
datasets[i].data.push([newData[j], newData[j + 1]]);
}
datasets[i].animator.steps = (newData.length / 2) - 1;
}
options.series.curvedLines.active = false;
var ani = $.plotAnimator($('#CAGraph'), [datasets[0]], options);
$("#CAGraph ").on("animatorComplete", function() {
chartsdone++;
if (chartsdone < chartcount) {
ani = $.plotAnimator($('#CAGraph'), datasets.slice(0, chartsdone + 1), options);
}
});

Amcharts: Interpolating step line chart values, show balloon of interpolated value

I'm a newbie at amCharts, trying to create a pretty simple step line chart.
I have data where the value stays constant a long time, and only records changes to the value, for example:
{
"timeOfDay": "18:20",
"value": 100
}, {
"timeOfDay": "19:40",
"value": 80
}, {
"timeOfDay": "21:40",
"value": 20
}, {
"timeOfDay": "22:40",
"value": 50
} // and so on
The chart should draw a horizontal line until the next change point, and then again until the next and so on, which I've managed to do. However, at the moment, it's only showing the balloon text at the data points and not where the cursor is, like this:
Here I'm hovering around time 20:15 though the screenshot taker didn't capture my cursor. The balloon text is displayed at the nearest data point. I'd want the balloon text to show up either at my cursor, or over the graph on the spot my cursor is in, and for it to show the time at the place where the cursor is in.
I know I could generate new data points in between the existing ones, but would rather not, since it would be pretty heavy of an operation since I want it to show the time with an accuracy of one second - that'd be thousands of data points an hour, and I'm trusting amCharts has an interpolation option for times hidden somewhere - I tried to search the docs / google for such an option, but didn't find one so far.
EDIT: Current chart code here: http://pastebin.com/BEZxgtCb
UPDATE: Managed to extract the time with the following functions and attaching an event listener to the chartCursor object - still can't get it to show anywhere else but on the predefined points on the graph though.
var parseDate = function(dateObj) {
return dateObj.getHours() + ":" + dateObj.getMinutes() + ":" + dateObj.getSeconds();
}
var handleMove = function(event) {
var time = event.chart.categoryAxis.coordinateToDate(event.x);
event.chart.graphs[0].balloonText = parseDate(time);
}
the balloon only shows up on actual data points which mean you need to inject them manually to show the balloon across the "interpolated" time. Following walkthrough your data, calculates the distance between the previous points and inject the amount of minutes in between.
var prevTime = undefined;
var prevValue = undefined;
var interpolate = [];
for ( var i1 = 0; i1 < chart.dataProvider.length; i1++ ) {
var item = chart.dataProvider[i1];
var curTime = AmCharts.stringToDate(item.timeOfDay,"JJ:NN")
var curVal = item.value;
if ( prevTime ) {
var distance = (Number(curTime) - Number(prevTime)) / 1000 / 60;
for ( var i2 = 0; i2 < distance; i2++ ) {
var newDate = new Date(prevTime);
newDate.setMinutes(prevTime.getMinutes() + i2);
if ( Number(newDate) < Number(curTime) ) {
interpolate.push({
timeOfDay: AmCharts.formatDate(newDate,"JJ:NN"),
value: prevValue
});
}
}
}
// NEW ONE
interpolate.push(item);
// FOR NEXT TIME
prevTime = curTime;
prevValue = curVal;
}
chart.dataProvider = interpolate;
Unfortunately there is no option to achieve that functionality.

How to add a new tick to the autogenerated ticks in flot

I want to add just a tick to the existing autogenerated ticks, how can I do it ?
This is the fiddle. I want to add tick 100 to the existing generated tick series. Can such a hack be done in flot ?
I was hoping this would be possible using the hooks functionality in flot but unfortunatly the ticks are generated and then the labels are added without any hooks in between.
So...
Your best bet would be to steal flots automatic tick generator, modify it to do what you want and then add it as the tick function in your options.
customTickGen = function (axis) {
/* BEGIN STOLEN FLOT METHOD */
var ticks = [],
start = axis.tickSize * Math.floor(axis.min / axis.tickSize),
i = 0,
v = Number.NaN,
prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push(v);
++i;
} while (v < axis.max && v != prev);
/* END OF STOLEN FLOT CODE */
/* Now find the spot and put a 100 in */
for (var i = 0; i < ticks.length - 1; i++){
if (ticks[i] < 100 && ticks[i+1] > 100){
ticks.splice(i,0,100);
break;
}
}
return ticks;
}
Here's a working fiddle.

All series data are equal highcharts

I have function for updating sensors. Idea is simple, i add new points from sensors (1 sensor = 1 line) and after appending I update charts. But something went wrong and all series equal to themself
seriesArr - just array of sensors like {"sensorId1", sensorId2 etc}
chartObj - object of charts like chart 1: { chart: highcharts,
seriesArr: seriesArr }
Simple explanations:
chartObject.chart.series[0].points = chartObject.chart.series[1].points = chartObject.chart.series[2].points = etc
My code:
updateAllCharts: function() {
var allCharts = this.charts;
console.log('charts');
for (var chart in allCharts) {
var chartObject = allCharts[chart];
for (var i = 0; i < chartObject.seriesArr.length; i++) {
var elemId = chartObject.seriesArr[i][0];
var val = this.sensors[elemId].get('value');
console.log(val);
if (val === undefined) { // if sensor cant get data
continue;
}
var now = new Date;
var x = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
var y = parseFloat(val);
chartObject.chart.series[i].addPoint([x, y], false, false);
console.log(x, y);
console.log(chartObject.chart.series[i].data);
}
}
for (var chart in allCharts) {
var chartObject = allCharts[chart];
chartObject.chart.redraw();
}
}
Screen:
UPDATE:
ProcessedDataX and Y arrays are changing, but there problem with points array, I always get some weird (maybe cached) points. WTF.
Playground
If you wanna play, i've setted up here jsfiddle, but actually it probably doesn't work. Can't add points to highchart object with setInterval.
JSFIDDLE
UPDATE2:
Actually it works fine in jsfiddle but i don't know wtf is going on in my project.
UPDATE3:
Found, that the same last point adds to each series. For example, series[i].lastPoints = series[n] , where n = last iteration.
Works, only if i REDRAW EVERYTIME AFTER ADDING EACH POINT. so bad solution, so bad.
just put true in parameter after Point object
chartObject.chart.series[z].addPoint(Point, true, false);
To all chart.redraw() you need to set isDirty flag
so try to use this code:
for (var chart in allCharts) {
var chartObject = allCharts[chart];
chartObject.yAxis[0].isDirty = true;
chartObject.chart.redraw();
}

Categories

Resources