Cytoscape Cola.js Layout edge length = text corpus visualisation - javascript

I want to set the edge length with the weight in my data.json.
Like in the cytoscape-spread demo the edge length should be longer depending on the weight.
"data" : {
"id" : "1965",
"source" : "108",
"target" : "149",
"shared_name" : "A (interacts with) B",
"shared_interaction" : "interacts with",
"name" : "A (interacts with) B",
"interaction" : "interacts with",
"SUID" : 1965,
"weight" : 342,
"selected" : false
},
"selected" : false
The weighting is the count how often A and B stands together in my text-corpus.
I tried different layouts but don't now how i can change the position, that the highest weight has the shortest distance.
At the moment i try to use the 'cose' Layout and set idealEdgeLength: function( edge ){ return edge.data('weight'); }
var options = {
name: 'cose',
// Called on `layoutready`
ready: function(){},
// Called on `layoutstop`
stop: function(){},
// Whether to animate while running the layout
animate: true,
// Whether to fit the network view after when done
fit: true,
// Padding on fit
padding: 30,
// Constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
boundingBox: undefined,
// Randomize the initial positions of the nodes (true) or use existing positions (false)
randomize: false,
// Ideal edge (non nested) length
idealEdgeLength: function( edge ){ return edge.data('weight'); },
};
cy.layout( options );
And cola.js edgeLength:
name: 'cola',
animate: true, // whether to show the layout as it's running
refresh: 1, // number of ticks per frame; higher is faster but more jerky
maxSimulationTime: 4000, // max length in ms to run the layout
ungrabifyWhileSimulating: false, // so you can't drag nodes during layout
fit: true, // on every layout reposition of nodes, fit the viewport
padding: 0, // padding around the simulation
boundingBox: undefined, // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
// layout event callbacks
ready: function(){}, // on layoutready
stop: function(){}, // on layoutstop
// positioning options
randomize: false, // use random node positions at beginning of layout
avoidOverlap: true, // if true, prevents overlap of node bounding boxes
handleDisconnected: true, // if true, avoids disconnected components from overlapping
nodeSpacing: function( node ){ return 10; }, // extra spacing around nodes
flow: undefined, // use DAG/tree flow layout if specified, e.g. { axis: 'y', minSeparation: 30 }
alignment: undefined, // relative alignment constraints on nodes, e.g. function( node ){ return { x: 0, y: 1 } }
// different methods of specifying edge length
// each can be a constant numerical value or a function like `function( edge ){ return 2; }`
edgeLength: function( edge ){var len = parseInt(edge.data('weight')); return len; }, // sets edge length directly in simulation
edgeSymDiffLength: undefined, // symmetric diff edge length in simulation
edgeJaccardLength: undefined, // jaccard edge length in simulation
// iterations of cola algorithm; uses default values on undefined
unconstrIter: undefined, // unconstrained initial layout iterations
userConstIter: undefined, // initial layout iterations with user-specified constraints
allConstIter: undefined, // initial layout iterations with all constraints including non-overlap
// infinite layout options
infinite: false // overrides all other options for a forces-all-the-time mode

If you want nodes to be pulled closer together if the edge weight is high, then the edge length needs to be inversely proportional to the weight, e.g. k / edge.data('weight') for some constant k. You'll have to experiment to find which k value works best for your data.
Take a look at the Cola demo source for an example. It uses this exact approach, and the slider just changes the k value.
http://js.cytoscape.org/demos/2ebdc40f1c2540de6cf0/

Related

Phaser 3 - Check group collision with world bounds

In my scenario, i create a ship according to player's preferences. The ship consists of the flag and the hull.
An example view
PROBLEM-1
Ship is an Arcade.Group and i want to prevent this group from going outside the borders of the world.
create(){
// Create a group for ship
this.shipGroup = this.physics.add.group()
// Add hull to shipGroup
this.shipGroup.create(400, 500, "1021")
// Add flag to shipGroup
const mainFlag = this.shipGroup.create(400, 500, "FA1")
mainFlag.setOrigin(0.5, 0.8)
// Set collision property to true of every object in shipGroup
this.shipGroup.children.each((item: any) =>
item.setCollideWorldBounds(true)
)
}
update(t: number, dt: number){
if (this.cursor.up.isDown) {
this.shipGroup.setVelocity(...)
}
else {
this.shipGroup.setVelocity(0, 0)
}
}
With this approach every object in group calculated seperately. After hitting the world boundary, the position of the objects is distorted.
PROBLEM-2
To avoid this i tried another approach. I add bounding box to group. Instead of check collision for every object, i will only check collision for bounding box.
create(){
// Create a group for ship
this.shipGroup = this.physics.add.group()
// Add bounding box for shipGroup
this.shipBox = this.shipGroup.create(400, 500, "bbox")
this.shipBox.setCollideWorldBounds(true)
this.shipBox.body.onWorldBounds = true
// Add hull to shipGroup
this.shipGroup.create(400, 500, "1021")
// Add flag to shipGroup
const mainFlag = this.shipGroup.create(400, 500, "FA1")
mainFlag.setOrigin(0.5, 0.8)
/*this.shipGroup.children.each((item: any) =>
item.setCollideWorldBounds(true)
)*/
}
update(t: number, dt: number){
if (this.cursor.up.isDown && !this.shipBox.body.checkWorldBounds()) {
this.shipGroup.setVelocity(...)
}
else {
this.shipGroup.setVelocity(0, 0)
}
}
The problem is checkWorldBounds() returns false even if shipBox hits world boundaries. But collision for shipBox is work.
checkWorldBounds()
Description: Checks for collisions between this Body and the world
boundary and separates them.
Returns: True if this Body is colliding with the world boundary.
How can i implement collision for group and world boundary?
P.S. : phaser version is 3.55.2
There are a few ways to solve/work around this issue, I personally would just use only one image why one physics-body (hull and flag combined) and just move that single image/texture, and switch the image, when needed.
That said, if you need to use the separate images, the easy way is to use a phaser container. (link to the documentation)
create a container
add the images to the container
set the size for the container (default size is width=0 height=0)
create a physics body for the container
done
A short demo:
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
physics: {
default: 'arcade',
arcade: {
gravity:{ y: 0 },
debug: true
}
},
scene: {
create
},
banner: false
};
function create () {
this.add.text(10,10, 'Ship with physics')
.setScale(1.5)
.setOrigin(0)
.setStyle({fontStyle: 'bold', fontFamily: 'Arial'});
let graphics = this.make.graphics();
graphics.fillStyle(0xffffff);
graphics.fillRect(0, 0, 10, 40);
graphics.generateTexture('ship', 10, 40);
graphics.fillStyle(0xff0000);
graphics.fillRect(0, 0, 30, 10);
graphics.generateTexture('flag', 30, 10);
graphics.generateTexture('flag2', 20, 6);
let hull = this.add.image(0, 0, 'ship')
let flag = this.add.image(0, -5, 'flag')
let flag2 = this.add.image(0, 10, 'flag2')
this.ship = this.add.container(100, 80, [ hull, flag, flag2]);
this.ship.setAngle(-90)
this.ship.setSize(40, 30)
this.physics.world.enable(this.ship);
this.ship.body.setVelocity(100, 0).setBounce(1, 1).setCollideWorldBounds(true);
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
Info: this demo is based partly from this official example

Different Depth In 3D BarChart in Highcharts

I know that I can set depth of all bars in Highcharts using depth property in column property of plotOptions likes the following code:
plotOptions: {
column : {
depth: 30
}
}
Or
# in R
hc_plotOptions(column = list(
depth = 30
)
The questions is how can I set different depth for each bar group in a bar chart (not one depth for all)? Solution can be in R (Highcharter) or in JS?
In core code the depth property is always taken from the series object options. Every group consists of the points with the same x values.
These 2 solutions came to my mind:
1. Modify the core code so that depth values are taken from points' configuration instead:
(function(H) {
(...)
H.seriesTypes.column.prototype.translate3dShapes = function() {
(...)
point.shapeType = 'cuboid';
shapeArgs.z = z;
shapeArgs.depth = point.options.depth; // changed from: shapeArgs.depth = depth;
shapeArgs.insidePlotArea = true;
(...)
};
})(Highcharts);
Series options:
series: [{
data: [{y: 5, depth: 50}, {y: 2, depth: 100}]
}, {
data: [{y: 13, depth: 50}, {y: 1, depth: 100}]
}]
Live demo: http://jsfiddle.net/kkulig/3pkon2Lp/
Docs page about overwriting core functions: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts
2. Create a separate series for every point.
depth property can be applied to a series so the modification of the core wouldn't be necessary. Every series is shown in legend by default so series will have to be properly connected using linkedTo property (so that the user doesn't see as many series as points).
Points can be modified before passing them to the chart constructor or dynamically handled in chart.events.load.
Live demo: http://jsfiddle.net/kkulig/37sot3am/
load: function() {
var chart = this,
newSeries = [],
merge = Highcharts.merge,
depths = [10, 100]; // depth values for subsequent x values
for (var i = chart.series.length - 1; i >= 0; i--) {
var s = chart.series[i];
s.data.forEach(function(p, i) {
// merge point options
var pointOptions = [merge(p.options, {
// x value doesn't have to appear in options so it needs to be added manually
x: p.x
})];
// merge series options
var options = merge(s.options, {
data: pointOptions,
depth: depths[i]
});
// mimic original series structure in the legend
if (i) {
options.linkedTo = ":previous"
}
newSeries.push(options);
});
s.remove(true);
}
newSeries.forEach((s) => chart.addSeries(s));
}
API reference:
https://api.highcharts.com/highcharts/plotOptions.series.linkedTo

Avoid float number labels on y-axis with dygraphs javascript and set different grid lines to secondary y axis

I have series with simple integer values. So there is no need to have float numbers as y-axis labels.
I use the axisLabelFormatter to convert y to integers. But the result is, that I have duplicated integer values on the y-axis.
How can I get a y-axis, which is labeled only with single integers at the correct place?
I would like to have the secondary y-axis with a different grid too
See also the example at https://jsfiddle.net/eM2Mg/9559/.
I have tried your example, modified it and I have got this result
I have modified your code the next way
var graph2 = new Dygraph(document.getElementById("graph2"), data, {
axes: {
y2: {
axisLabelFormatter: function(y) {
return texts[y] || parseInt(y);
},
drawGrid: true,
independentTicks: true,
pixelsPerLabel: 100,
gridLinePattern: [2,2]
}
},
legend: "always",
series: {
"State": {
axis: "y2",
strokeWidth: 2,
stepPlot: true,
}
},
strokeWidth: 2,
title: "my try to get what I want"
});
I have set the option drawGrid and independentLabels to true.
It is necessary to adjust the pixelsPerLabel to the size you think the 3 values auto, on, off are better shown.
And the grid patterLine to show a different grid for the right y axis.
You can also remove the drawGrid if you consider it look better without the grid.
I hope this could be a solution for you! Regards!

Cytoscape.js Preset Layout Documentation

I have a cytoscape.js graph that renders. I'm interested in leveraging the preset layout to place the nodes. The cytoscape.js documentation shows the following for the preset layout:
var options = {
name: 'preset',
positions: undefined, // map of (node id) => (position obj); or function(node){ return somPos; }
zoom: undefined, // the zoom level to set (prob want fit = false if set)
pan: undefined, // the pan level to set (prob want fit = false if set)
fit: true, // whether to fit to viewport
padding: 30, // padding on fit
animate: false, // whether to transition the node positions
animationDuration: 500, // duration of animation in ms if enabled
animationEasing: undefined, // easing of animation if enabled
ready: undefined, // callback on layoutready
stop: undefined // callback on layoutstop
};
Can some one help me understand or give an example of what the documentation means when it says the following
// map of (node id) => (position obj); or function(node){ return somPos; }
I store all the nodes in a MySQL database table with the following columns
id, origin, destination, x position, y position
Does the cytoscape.js positions take a dictionary that looks like this:
{'id': 1, {'x':10, 'y':45}}, {'id': 2, {'x':21, 'y':32}} etc?
This means when the positions is set as undefined you need to create a function to get the positions of each node.
For example:
cy.nodes().forEach(function(n){
var x = n.data("x");
var y = n.data("y");
});
This should return your node position.
EDIT
You can set the node position when you are creating it. For example:
var elements;
elements: [{"data":{"id":"yourID","name":"name"},"position"{"x":"0.0","y":"0.0"}}];
For more, see this Demo on Cytoscape js site. Here they set the position manually.

Pass parameter to c3js tooltop after .generate() and before .load()

I'm trying to graph out metrics that don't have any relation to one another, so instead of plotting out the actual values, I've calculated an alternate set of values that are scaled between 0-1 like a percentage.
For example: [1, 2, 5] => [0.2, 0.4, 1]
So now I have 2 sets of data - the original and scaled versions. I have the scaled version plotting on to my graph just fine, but I want the tooltip to show the original value to the user. See what I mean?
I checked out http://c3js.org/samples/tooltip_format.html, which shows you can set tooltip as a function when you initially generate the C3 object. But I want to change the tooltip later on after I recalculate my original/scaled values and re-load() the graph.
All attempts I've made to explicitly change myGraph.tooltip.format.value = function (...) {...} after initially setting myGraph = C3.generate({...}) have been unsuccessful.
Any ideas how I can accomplish this without having to regenerate the graph from scratch every time?
You need to override internal.getTooltipContent
var data = ['data1', 30000, 20000, 10000, 40000, 15000, 250000];
// simple fake data
var fakeData = data.map(function (d, i) {
return i ? (d / 100) : d;
})
var chart = c3.generate({
data: {
columns: [
fakeData,
['data2', 100, 200, 100, 40, 150, 250]
],
}
});
// do code to take over mars and plant potatoes
// save the original
var originalGetTooltipContent = chart.internal.getTooltipContent;
chart.internal.getTooltipContent = function (data, defaultTitleFormat, defaultValueFormat, color) {
// we modified the first series, so let's change that alone back
var originalValue = {
id: data[0].id,
index: data[0].index,
name: data[0].name,
// unfaked
value: data[0].value * 100,
x: data[0].x
};
var originalValues = data.map(function (d, i) {
return i ? d : originalValue;
})
return originalGetTooltipContent.call(this, originalValues, defaultTitleFormat, defaultValueFormat, color)
}
I assume you are already doing something about the scaled y axis label?
Fiddle - http://jsfiddle.net/puf248en/
Thanks potatopeelings,
I did turn out solving this one by simply loading the form data in all at once, and then programmatically show/hide certain metrics. So that allowed me to use all the generate() options as intended.
Did try out your solution, and it seemed to do the trick till I found the simpler option. Thanks!

Categories