How to create zoomable plot object using flot library in javascript? - javascript

Here is my code so far. I can see the selection rectangle, but zooming isn't happening.
what have I did wrong?
function Plot(container, data) {
this.options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
tickDecimals: 0,
tickSize: 1
},
selection: { mode: "xy" }
}
console.log("script is running")
this.data = []
this.container = container;
this.plot = $.plot(container, this.data, this.options);
this.url = '/sensor/oscillogram_debug_data/'+110;
this.container.bind("plotselected", this.zoom);
this.zoom = function(event, reanges) {
if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)
ranges.xaxis.to = ranges.xaxis.from + 0.00001;
if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)
ranges.yaxis.to = ranges.yaxis.from + 0.00001;
this.plot = $.plot(this.container, this.plot.getData(),
$.extend(true, {}, this.options, {
xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
}));
}
}
var plot = new Plot($("#output_plot_container"));
var updateChart = function() {
$.getJSON(plot.url, function(newdata) {
for (var f_id in newdata)
if (newdata.hasOwnProperty(f_id)) {
if (f_id='demodulated') {
// plot.plot.setData([newdata[f_id]])
// plot.plot.setupGrid()
// plot.plot.draw()
}
}
})
}

A few problems here:
1.) You are binding to this.zoom before it exists, reverse those calls (and note typo in "reanges"):
this.zoom = function(event, ranges) {
....
this.container.bind("plotselected", this.zoom);
2.) Your attempt at some sort of OO scoping within this.zoom just isn't going to work. Once that function is bound, it doesn't have access to it's parent scope. If you want the this to be available in the bind, you can pass it in as eventData:
this.container.bind("plotselected", {obj: this}, this.zoom); // and replace the this in this.zoom with obj
Here's a working fiddle.

Related

How do you apply Smart Routing on links with ports on JointJS?

I am trying to apply smart routing of links with the use of ports using JointJS. This documentation shows the one I am trying to achieve. The example on the docs though shows only the programmatic way of adding Link from point A to point B. How do you do this with the use of ports?
Here's my code: JSFiddle.
HTML:
<html>
<body>
<button id="btnAdd">Add Table</button>
<div id="dbLookupCanvas"></div>
</body>
</html>
JS
$(document).ready(function() {
$('#btnAdd').on('click', function() {
AddTable();
});
InitializeCanvas();
// Adding of two sample tables on first load
AddTable(50, 50);
AddTable(250, 50);
});
var graph;
var paper
var selectedElement;
var namespace;
function InitializeCanvas() {
let canvasContainer = $('#dbLookupCanvas').parent();
namespace = joint.shapes;
graph = new joint.dia.Graph({}, {
cellNamespace: namespace
});
paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
}
});
//Dragging navigation on canvas
var dragStartPosition;
paper.on('blank:pointerdown',
function(event, x, y) {
dragStartPosition = {
x: x,
y: y
};
}
);
paper.on('cell:pointerup blank:pointerup', function(cellView, x, y) {
dragStartPosition = null;
});
$("#dbLookupCanvas")
.mousemove(function(event) {
if (dragStartPosition)
paper.translate(
event.offsetX - dragStartPosition.x,
event.offsetY - dragStartPosition.y);
});
// Remove links not connected to anything
paper.model.on('batch:stop', function() {
var links = paper.model.getLinks();
_.each(links, function(link) {
var source = link.get('source');
var target = link.get('target');
if (source.id === undefined || target.id === undefined) {
link.remove();
}
});
});
paper.on('cell:pointerdown', function(elementView) {
resetAll(this);
let isElement = elementView.model.isElement();
if (isElement) {
var currentElement = elementView.model;
currentElement.attr('body/stroke', 'orange');
selectedElement = elementView.model;
} else
selectedElement = null;
});
paper.on('blank:pointerdown', function(elementView) {
resetAll(this);
});
$('#dbLookupCanvas')
.attr('tabindex', 0)
.on('mouseover', function() {
this.focus();
})
.on('keydown', function(e) {
if (e.keyCode == 46)
if (selectedElement) selectedElement.remove();
});
}
function AddTable(xCoord = undefined, yCoord = undefined) {
// This is a sample database data here
let data = [
{columnName: "radomData1"},
{columnName: "radomData2"}
];
if (xCoord == undefined && yCoord == undefined)
{
xCoord = 50;
yCoord = 50;
}
const rect = new joint.shapes.standard.Rectangle({
position: {
x: xCoord,
y: yCoord
},
size: {
width: 150,
height: 200
},
ports: {
groups: {
'a': {},
'b': {}
}
}
});
$.each(data, (i, v) => {
const port = {
group: 'a',
args: {}, // Extra arguments for the port layout function, see `layout.Port` section
label: {
position: {
name: 'right',
args: {
y: 6
} // Extra arguments for the label layout function, see `layout.PortLabel` section
},
markup: [{
tagName: 'text',
selector: 'label'
}]
},
attrs: {
body: {
magnet: true,
width: 16,
height: 16,
x: -8,
y: -4,
stroke: 'red',
fill: 'gray'
},
label: {
text: v.columnName,
fill: 'black'
}
},
markup: [{
tagName: 'rect',
selector: 'body'
}]
};
rect.addPort(port);
});
rect.resize(150, data.length * 40);
graph.addCell(rect);
}
function resetAll(paper) {
paper.drawBackground({
color: 'white'
});
var elements = paper.model.getElements();
for (var i = 0, ii = elements.length; i < ii; i++) {
var currentElement = elements[i];
currentElement.attr('body/stroke', 'black');
}
var links = paper.model.getLinks();
for (var j = 0, jj = links.length; j < jj; j++) {
var currentLink = links[j];
currentLink.attr('line/stroke', 'black');
currentLink.label(0, {
attrs: {
body: {
stroke: 'black'
}
}
});
}
}
Any help would be appreciated. Thanks!
The default link created when you draw a link from a port is joint.dia.Link.
To change this you can use the defaultLink paper option, and configure the router you would like.
defaultLink documentation reference
const paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
},
defaultLink: () => new joint.shapes.standard.Link({
router: { name: 'manhattan' },
connector: { name: 'rounded' },
})
});
You could also provide several default options in the paper.
defaultLink: () => new joint.shapes.standard.Link(),
defaultRouter: { name: 'manhattan' },
defaultConnector: { name: 'rounded' }

Highcharts add new data to series after click

I'm trying to add a new point (to series data) on spline chart after clicking in the place where I'm clicked on the line. But point click event doesn't return xAxis, yAxis (only in pixels). I decide to calculate the difference between point pixels position and click, but point adds not on the click place. What I'm doing wrong? How to handle this?
My JS
var setDragStatus = function (status) {
document.getElementById('dragstatus').innerHTML = status;
};
Highcharts.chart('container', {
title: {
text: 'Spline Drag&Drop'
},
plotOptions: {
series: {
turboThreshold: 4,
minPointLength: 5,
dragDrop: {
draggableY: true,
dragMaxY: 1,
},
point: {
events: {
click: function (e) {
let pointPlotX = e.point.plotX
let pointPlotY = e.point.plotY
let pointX = e.point.x
let pointY = e.point.y
let clickX = e.chartX
let clickY = e.chartY
let pointDiffX = clickX / pointPlotX
let pointDiffY = clickY / pointPlotY
let newPointX = pointX * pointDiffX
let newPointY = pointDiffY * pointY
this.series.addPoint([newPointX, newPointY])
}
}
},
}
},
xAxis: {
reversed: false,
showFirstLabel: false,
showLastLabel: true
},
series: [
{
name: 'spline top',
data: [0, 0.3, 0.6, 1],
type: 'spline'
}
]
}
);
Result - https://jsfiddle.net/antiaf/1hfuyjbr/
To calculate x and y values you can use toValue Axis method:
plotOptions: {
series: {
...,
point: {
events: {
click: function(e) {
let series = this.series,
yAxis = series.yAxis,
xAxis = series.xAxis,
newPointX = xAxis.toValue(e.chartX),
newPointY = yAxis.toValue(e.chartY);
this.series.addPoint([newPointX, newPointY])
}
}
}
}
}
Live demo: https://jsfiddle.net/BlackLabel/hg81o4ej/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Axis#toValue

Why highchart returning " Typeerror : undefined variable byte "?

I am trying to draw a graph with the help of high chart and also using load event I am trying to add values after each 1 second to the graph.
In this graph I also want to show axis as Mb,Kb,,Gb data. So I am writing a function to return the byte values as Mb,Kb,Gb (for both series and tooltip)
This is my code :
// highchart options :
var series1, series2 ;
var chart = {
type: 'bar',
events: {
load: function () {
// set up the updating of the chart each second
series1 = this.series[0];
series2 = this.series[1];
setInterval(function () {
add_function();
}, 1000);//call function each 1 second
}
}
};
var tooltip = {
enabled: true,
formatter: function() { return fbytes(this.y,2);}
};
var plotOptions = {
bar: {
},
series: {
dataLabels: {
enabled: true,
formatter: function() { return fbytes(this.y,2);},
inside: true,
style: {fontWeight: 'number'}
},
pointPadding: 0,
pointWidth:38
},
column : {
grouping: true
}
};
series= [
{
name: 'old',
color: '#f9a80e',
data: [,]
},
{
name: 'new',
color: '#89897f',
data: [,]
}
];
and the load event function is :
Array.max = function (array) {
return Math.max.apply(Math, array);
};
Array.min = function (array) {
return Math.min.apply(Math, array);
};
add_function()
{
var arr[];
//getting array values here
var min_value = Array.min(arr);
var max_value = Array.max(arr);
var chart2 = $('#container').highcharts();
chart2.yAxis[0].update({max:max_value, min: 0}, true);
series1.setData([arr[0],arr[2]], true, true);
series2.setData([arr[1],arr[3]], true, true);
}
and the conversion function :
function fbytes(bytes, precision) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
var posttxt = 0;
if (bytes == 0) return '0 Bytes';
if (bytes < 1024) {
return Number(bytes) + " " + sizes[posttxt];
}
while( bytes >= 1024 ) {
posttxt++;
bytes = bytes / 1024;
}
return Math.round(bytes.toPrecision(precision)) + " " + sizes[posttxt];
}
my logic : i got some array values randomly and i am displaying this data on the graph .
problem facing : I didn't get this.y value inside series . When i print this value inside
series: {
dataLabels: {
enabled: true,
formatter: function() { return fbytes(this.y,2);},
inside: true,
style: {fontWeight: 'number'}
},
I am getting this.y = undefined . What is happening ?
Any mistake in the code ? Any suggestions ?
I created demo using your code and modified add_function() a little bit. Did you mean something like this?
function add_function(series1, series2) {
var chart2 = $('#container').highcharts(),
increment = 1024,
min_value,
max_value,
newVal1 = [],
newVal2 = [];
if (!series1.data.length && !series2.data.length) {
var arr = [512, 128, 1024, 0];
min_value = Array.min(arr);
max_value = Array.max(arr);
newVal1 = [arr[0], arr[2]];
newVal2 = [arr[1], arr[3]];
} else {
series1.yData.forEach(function(sEl, sInx) {
newVal1.push(sEl + increment);
});
series2.yData.forEach(function(sEl, sInx) {
newVal2.push(sEl + increment);
});
max_value = Array.max(newVal1.concat(newVal2));
}
chart2.yAxis[0].update({
max: max_value,
min: 0
}, true);
series1.setData(newVal1, true, true);
series2.setData(newVal2, true, true);
}
Example:
http://jsfiddle.net/js3g311q/

HTML Content to Javascript Code

I am trying to take the content in a div tag and turn it into Javascript code. The reason for this is to take the div information and convert it into a Highchart data series.
HTML Content
<div id="data">{name: 'Point 1',x: Date.UTC(2014, 11, 1),x2: Date.UTC(2014, 11, 8),y: 0},{name: 'Point 2',x: Date.UTC(2014, 12, 1),x2: Date.UTC(2014, 12, 8),y: 0},</div>
Javascript/snippet Content
$(function () {
var newdata = $("#data");
(function (H) {
var defaultPlotOptions = H.getOptions().plotOptions,
columnType = H.seriesTypes.column,
each = H.each;
defaultPlotOptions.xrange = H.merge(defaultPlotOptions.column, {});
H.seriesTypes.xrange = H.extendClass(columnType, {
type: 'xrange',
parallelArrays: ['x', 'x2', 'y'],
requireSorting: false,
animate: H.seriesTypes.line.prototype.animate,
/**
* Borrow the column series metrics, but with swapped axes. This gives free access
* to features like groupPadding, grouping, pointWidth etc.
*/
getColumnMetrics: function () {
var metrics,
chart = this.chart;
function swapAxes() {
each(chart.series, function (s) {
var xAxis = s.xAxis;
s.xAxis = s.yAxis;
s.yAxis = xAxis;
});
}
swapAxes();
this.yAxis.closestPointRange = 1;
metrics = columnType.prototype.getColumnMetrics.call(this);
swapAxes();
return metrics;
},
translate: function () {
columnType.prototype.translate.apply(this, arguments);
var series = this,
xAxis = series.xAxis,
metrics = series.columnMetrics;
H.each(series.points, function (point) {
var barWidth = xAxis.translate(H.pick(point.x2, point.x + (point.len || 0))) - point.plotX;
point.shapeArgs = {
x: point.plotX,
y: point.plotY + metrics.offset,
width: barWidth,
height: metrics.width
};
point.tooltipPos[0] += barWidth / 2;
point.tooltipPos[1] -= metrics.width / 2;
});
}
});
/**
* Max x2 should be considered in xAxis extremes
*/
H.wrap(H.Axis.prototype, 'getSeriesExtremes', function (proceed) {
var axis = this,
dataMax = Number.MIN_VALUE;
proceed.call(this);
if (this.isXAxis) {
each(this.series, function (series) {
each(series.x2Data || [], function (val) {
if (val > dataMax) {
dataMax = val;
}
});
});
if (dataMax > Number.MIN_VALUE) {
axis.dataMax = dataMax;
}
}
});
}(Highcharts));
// THE CHART
$('#container').highcharts({
chart: {
type: 'xrange'
},
title: {
text: 'Highcharts X-range study'
},
plotOptions: {
series: {
events: {
mouseOver: function () {
var cur = this;
Highcharts.each(this.chart.series, function (series) {
if (series !== cur) {
series.group.animate({
opacity: 0.2
}, {
duration: 150
});
} else {
series.group.animate({
opacity: 1
}, {
duration: 150
});
}
});
},
mouseOut: function () {
this.group.animate({
opacity: 1
}, {
duration: 150
});
}
}
}
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: '',
categories: [],
},
series: [$(newdata).text()]
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="data">{name: 'Point 1',x: Date.UTC(2014, 11, 1),x2: Date.UTC(2014, 11, 8),y: 0},{name: 'Point 2',x: Date.UTC(2014, 12, 1),x2: Date.UTC(2014, 12, 8),y: 0},</div>
It pulls the content as text and does not create it as code. Can this be done?
If all of the contents of the #data element is properly formatted, all you'll actually have to do is grab the inner html of that element and parse it into JSON.
// This is the contents of #data as a String
var data_as_a_string = document.getElementById("data").innerHTML;
// And here it is "in javascript" as an Object
var data_as_an_object = JSON.parse( data_as_a_string );
you can try eval function
The eval() function evaluates JavaScript code represented as a string.
eval(string)
eval(" var s='hello'; alert(s);");

Plotly update data

Okay so i have the following code:
var element = document.getElementById(scope.changeid);
function getData(division,redraw) {
var employeeData = [];
if (!division) {
$http.get(api.getUrl('competenceUserAverageByMyDivisions', null)).success(function (response) {
processData(response,redraw);
});
}
else {
$http.get(api.getUrl('competenceUserAverageByDivision', division)).success(function (response) {
processData(response,redraw);
})
}
}
function processData(data,redraw) {
var y = [],
x1 = [],
x2 = [];
data.forEach(function (item) {
y.push(item.user.profile.firstname);
x1.push(item.current_level);
x2.push(item.expected);
});
var charData = [{
x: x1,
y: y,
type: 'bar',
orientation: 'h',
name: 'Nuværende'
}, {
x: x2,
y: y,
type: 'bar',
orientation: 'h',
name: 'Forventet'
}],
layout = {
barmode: 'stack',
legend: {
traceorder: 'reversed',
orientation: 'h'
}
};
if(!redraw){
Plotly.plot(element, charData, layout);
}
else
{
Plotly.redraw(element,charData,layout);
}
}
scope.$watch('divisionId', function (newValue, oldValue) {
if (newValue) {
getData(newValue.id,true);
}
}, true);
getData(null,false);
Which creates the following chart:
Now as you can see ive added a watcher
scope.$watch('divisionId', function (newValue, oldValue) {
if (newValue) {
getData(newValue.id,true);
}
}, true);
Now when i trigger this it should update the chart and call Plotly.redraw(element,charData,layout);
However when it does this the chart does not change at all. There is no error in the console so i am not quite sure what to do?
Plotly.redraw(gd) is the right way.
But you call Plotly.redraw incorrectly.
The right way is update the data object, instead of new a data object.
var data = [{
x: ['VALUE 1'], // in reality I have more values...
y: [20],
type: 'bar'
}];
Plotly.newPlot('PlotlyTest', data);
function adjustValue1(value) {
data[0]['y'][0] = value;
Plotly.redraw('PlotlyTest');
}
Ref: http://www.mzan.com/article/35946484-most-performant-way-to-update-graph-with-new-data-with-plotly.shtml
I found the answer to the question.
Apprently i needed to use:
Plotly.newPlot(element,charData,layout);
instead of redraw
According to a Plotly community moderator (see the first answer here), Plotly.restyle is faster than Plotly.redraw and Plotly.newPlot.
Example taken from the link:
var data = [{
x: ['VALUE 1'], // in reality I have more values...
y: [20],
type: 'bar'
}];
Plotly.newPlot('PlotlyTest', data);
function adjustValue1(value)
{
Plotly.restyle('PlotlyTest', 'y', [[value]]);
}
The extendTraces function should be what you are aiming for. It can add data points to your graph and redraws it. In contrast to redraw (#Honghe.Wu Answer), you do not need to update the reference when using extendTraces.
[extendTraces] This function has comparable performance to Plotly.react and is faster than redrawing the whole plot with Plotly.newPlot.
https://plot.ly/javascript/plotlyjs-function-reference/#plotlyextendtraces
Example usage
// initialise some data beforehand
var y = [];
for (var i = 0; i < 20; i ++) {
y[i] = Math.random();
}
var trace = {
// x: x,
y: y,
type: 'bar',
};
var data = [trace];
// create the plotly graph
Plotly.newPlot('graph', data);
setInterval(function() {
// add data to the trace via function call
Plotly.extendTraces('graph', { y: [[getData()]] }, [0]);
// y.push(getData()); Plotly.redraw('graph'); //similar effect
}, 400);
function getData() {
return Math.random();
}

Categories

Resources