Json data not able to display as a graph using sigma.js - javascript

I'm using this code to display JSON file data as a graph but it is not displaying anything.
How to display this JSON data using sigma.js in graph form.
Any pointers would be appreciated!
Code
var data = {
"UniversalWord": {
"UniversalWord": [{
"uw_id": 1,
"HeadWord": {
"word": "aare"
},
"Restriction": {
"SemanticRelations": {
"feat": [{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
}
]
}
},
"NLDescription": {
"Gloss": {
"feat": {
"att": "Description",
"val": "\"A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE\""
}
},
"Lemma": {
"feat": {
"att": "word",
"val": "aare"
}
},
"Example": {
"feat": {
"att": "description",
"val": "\"\""
}
}
},
"MetaInfo": {
"Frequency": {
"freq": ""
},
"UWSource": {
"Source_id": "WORDNET"
}
}
}]
}
}
// these are just some preliminary settings
var g = {
nodes: [],
edges: []
};
// Create new Sigma instance in graph-container div (use your div name here)
s = new sigma({
graph: g,
container: 'graph-container',
renderer: {
container: document.getElementById('graph-container'),
type: 'canvas'
},
settings: {
minNodeSize: 8,
maxNodeSize: 16
}
});
// first you load a json with (important!) s parameter to refer to the sigma instance
sigma.parsers.json(
//'test.json',
data,
s,
function() {
// this below adds x, y attributes as well as size = degree of the node
var i,
nodes = s.graph.nodes(),
len = nodes.length;
for (i = 0; i < len; i++) {
nodes[i].x = Math.random();
nodes[i].y = Math.random();
nodes[i].size = s.graph.degree(nodes[i].id);
nodes[i].color = nodes[i].center ? '#333' : '#666';
}
// Refresh the display:
s.refresh();
// ForceAtlas Layout
s.startForceAtlas2();
}
);
.link {
fill: none;
stroke: #000;
}
.node {
stroke: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/sigma.js/1.2.0/sigma.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sigma.js/1.2.0/plugins/sigma.parsers.json.min.js"></script>
<div id="graph-container"></div>

Related

How to validate for un-connected edges to cell in mxgraph

Hi i'm facing problem with validation for un-connected edges to cells in mxgraph
below image will show you my expectation:
Question: whenever i press validate button un-connected edges and cells must be highlighted with red color.
For full view Codepen:https://codepen.io/eabangalore/pen/pmELpL?editors=1100
NOTE: PLEASE SEE CODEPEN LINK (https://codepen.io/eabangalore/pen/pmELpL?editors=1100) as BELOW CODE IS NOT WORKING
Full Code:
<!--
Copyright (c) 2006-2013, JGraph Ltd
Dynamic toolbar example for mxGraph. This example demonstrates changing the
state of the toolbar at runtime.
-->
<html>
<head>
<title>Toolbar example for mxGraph</title>
<!-- Sets the basepath for the library if not in same directory -->
<script type="text/javascript">
mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
function setGraphData(){
var graphState ={"tagName":"mxGraphModel","children":[{"tagName":"root","children":[{"tagName":"mxCell","attributes":{"id":"0"}},{"tagName":"mxCell","attributes":{"id":"1","parent":"0"}},{"tagName":"mxCell","attributes":{"id":"2","value":"A","style":"","parent":"1","vertex":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x":"271.56251525878906","y":"82.44792175292969","width":"100","height":"40","as":"geometry"}}]},{"tagName":"mxCell","attributes":{"id":"3","value":"B","style":"","parent":"1","vertex":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x":"678.2291717529297","y":"106.89236450195312","width":"100","height":"40","as":"geometry"}}]},{"tagName":"mxCell","attributes":{"id":"4","value":"Bangalore","parent":"1","edge":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x":"0.0511","y":"-20","relative":"1","as":"geometry"},"children":[{"tagName":"mxPoint","attributes":{"x":"370.06251525878906","y":"109.95338610053051","as":"sourcePoint"}},{"tagName":"mxPoint","attributes":{"x":"676.7291717529297","y":"128.3869001543523","as":"targetPoint"}},{"tagName":"mxPoint","attributes":{"as":"offset"}}]}]},{"tagName":"mxCell","attributes":{"id":"5","value":"C","style":"","parent":"1","vertex":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x":"1013.7847747802734","y":"83.55902862548828","width":"100","height":"40","as":"geometry"}}]},{"tagName":"mxCell","attributes":{"id":"6","parent":"1","source":"3","target":"5","edge":"1"},"children":[{"tagName":"mxGeometry","attributes":{"relative":"1","as":"geometry"}}]},{"tagName":"mxCell","attributes":{"id":"7","value":"Not Connected","style":"","vertex":"1","parent":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x":"552","y":"267.640625","width":"100","height":"40","as":"geometry"}}]},{"tagName":"mxCell","attributes":{"id":"8","value":"Edge Not connected must highlight in red color","edge":"1","parent":"1","source":"5"},"children":[{"tagName":"mxGeometry","attributes":{"relative":"1","as":"geometry"},"children":[{"tagName":"mxPoint","attributes":{"x":"740","y":"260","as":"targetPoint"}}]}]}]}]};
localStorage.setItem('graphState',JSON.stringify(graphState));
}
function html2json(html){
if(html.nodeType==3){
return {
"tagName":"#text",
"content":html.textContent
}
}
var element = {
"tagName":html.tagName
};
if(html.getAttributeNames().length>0){
element.attributes = html.getAttributeNames().reduce(
function(acc,at){acc[at]=html.getAttribute(at); return acc;},
{}
);
}
if(html.childNodes.length>0){
element.children = Array.from(html.childNodes)
.filter(
function(el){
return el.nodeType!=3
||el.textContent.trim().length>0
})
.map(function(el){return html2json(el);});
}
return element;
}
function json2html(json){
var xmlDoc = document.implementation.createDocument(null, json.tagName);
var addAttributes = function(jsonNode, node){
if(jsonNode.attributes){
Object.keys(jsonNode.attributes).map(
function(name){
node.setAttribute(name,jsonNode.attributes[name]);
}
);
}
}
var addChildren = function(jsonNode,node){
if(jsonNode.children){
jsonNode.children.map(
function(jsonChildNode){
json2htmlNode(jsonChildNode,node);
}
);
}
}
var json2htmlNode = function(jsonNode,parent){
if(jsonNode.tagName=="#text"){
return xmlDoc.createTextNode(jsonNode.content);
}
var node = xmlDoc.createElement(jsonNode.tagName);
addAttributes(jsonNode,node);
addChildren(jsonNode,node);
parent.appendChild(node);
}
addAttributes(json,xmlDoc.firstElementChild);
addChildren(json,xmlDoc.firstElementChild);
return xmlDoc;
}
</script>
<!-- Loads and initializes the library -->
<script type="text/javascript" src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>
<!-- Example code -->
<script type="text/javascript">
// Program starts here. Creates a sample graph in the
// DOM node with the specified ID. This function is invoked
// from the onLoad event handler of the document (see below).
function main()
{
setGraphData();
// Checks if browser is supported
if (!mxClient.isBrowserSupported())
{
// Displays an error message if the browser is
// not supported.
mxUtils.error('Browser is not supported!', 200, false);
}
else
{
// Defines an icon for creating new connections in the connection handler.
// This will automatically disable the highlighting of the source vertex.
mxConnectionHandler.prototype.connectImage = new mxImage('images/connector.gif', 16, 16);
// Creates the div for the toolbar
var tbContainer = document.createElement('div');
tbContainer.style.position = 'absolute';
tbContainer.style.overflow = 'hidden';
tbContainer.style.padding = '2px';
tbContainer.style.left = '0px';
tbContainer.style.top = '0px';
tbContainer.style.width = '24px';
tbContainer.style.bottom = '0px';
document.body.appendChild(tbContainer);
// Creates new toolbar without event processing
var toolbar = new mxToolbar(tbContainer);
toolbar.enabled = false
// Creates the div for the graph
var container = document.createElement('div');
container.style.position = 'absolute';
container.style.overflow = 'hidden';
container.style.left = '24px';
container.style.top = '0px';
container.style.right = '0px';
container.style.bottom = '0px';
container.style.background = 'url("editors/images/grid.gif")';
document.body.appendChild(container);
// Workaround for Internet Explorer ignoring certain styles
if (mxClient.IS_QUIRKS)
{
document.body.style.overflow = 'hidden';
new mxDivResizer(tbContainer);
new mxDivResizer(container);
}
// Creates the model and the graph inside the container
// using the fastest rendering available on the browser
var model = new mxGraphModel();
var graph = new mxGraph(container, model);
// Enables new connections in the graph
graph.setConnectable(true);
graph.setMultigraph(false);
// Stops editing on enter or escape keypress
var keyHandler = new mxKeyHandler(graph);
var rubberband = new mxRubberband(graph);
var addVertex = function(icon, w, h, style)
{
var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
vertex.setVertex(true);
var img = addToolbarItem(graph, toolbar, vertex, icon);
img.enabled = true;
graph.getSelectionModel().addListener(mxEvent.CHANGE, function()
{
var tmp = graph.isSelectionEmpty();
mxUtils.setOpacity(img, (tmp) ? 100 : 20);
img.enabled = tmp;
});
};
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rectangle.gif', 100, 40, '');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rounded.gif', 100, 40, 'shape=rounded');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/ellipse.gif', 40, 40, 'shape=ellipse');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rhombus.gif', 40, 40, 'shape=rhombus');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/triangle.gif', 40, 40, 'shape=triangle');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/cylinder.gif', 40, 40, 'shape=cylinder');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/actor.gif', 30, 40, 'shape=actor');
// read state on load
if(window.localStorage.graphState){
var doc = json2html(JSON.parse(localStorage.graphState));
var dec = new mxCodec(doc);
dec.decode(doc.documentElement, graph.getModel());
}
// save state on change
graph.getModel().addListener('change',function(){
var codec = new mxCodec();
window.localStorage.graphState = JSON.stringify(html2json(codec.encode(
graph.getModel()
)));
});
}
}
function addToolbarItem(graph, toolbar, prototype, image)
{
// Function that is executed when the image is dropped on
// the graph. The cell argument points to the cell under
// the mousepointer if there is one.
var funct = function(graph, evt, cell, x, y)
{
graph.stopEditing(false);
var vertex = graph.getModel().cloneCell(prototype);
vertex.geometry.x = x;
vertex.geometry.y = y;
graph.addCell(vertex);
graph.setSelectionCell(vertex);
}
// Creates the image which is used as the drag icon (preview)
var img = toolbar.addMode(null, image, function(evt, cell)
{
var pt = this.graph.getPointForEvent(evt);
funct(graph, evt, cell, pt.x, pt.y);
});
// Disables dragging if element is disabled. This is a workaround
// for wrong event order in IE. Following is a dummy listener that
// is invoked as the last listener in IE.
mxEvent.addListener(img, 'mousedown', function(evt)
{
// do nothing
});
// This listener is always called first before any other listener
// in all browsers.
mxEvent.addListener(img, 'mousedown', function(evt)
{
if (img.enabled == false)
{
mxEvent.consume(evt);
}
});
mxUtils.makeDraggable(img, graph, funct);
return img;
}
</script>
</head>
<!-- Calls the main function after the page has loaded. Container is dynamically created. -->
<body onload="main();" >
</body>
</html>
Please help me thanks in advance!!!
Edit: As per the comment, to validate the cells not connected to the parent cell or its branches, we can use a recursive function checking each connected edge starts from the parent cell and so on.
Due to the limit of characters, the original code snippet is removed.
.not_connected * {
color: red;
font-color: red;
stroke: red;
stroke-color: red;
}
<!--
Copyright (c) 2006-2013, JGraph Ltd
Dynamic toolbar example for mxGraph. This example demonstrates changing the
state of the toolbar at runtime.
-->
<html>
<head>
<title>Toolbar example for mxGraph</title>
</head>
<!-- Calls the main function after the page has loaded. Container is dynamically created. -->
<body onload="main();">
<button style="position:absolute; left:300px;padding:8px 40px;background:orangered;color:#fff;outline:none;border:none;z-index:100;" id="validate_btn">Validate</button>
</body>
</html>
<!-- Sets the basepath for the library if not in same directory -->
<script type="text/javascript">
mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
var graphStateJSON;
var graph;
function setGraphData() {
var graphState = {
"tagName": "mxGraphModel",
"children": [{
"tagName": "root",
"children": [{
"tagName": "mxCell",
"attributes": {
"id": "0"
}
}, {
"tagName": "mxCell",
"attributes": {
"id": "1",
"parent": "0"
}
}, {
"tagName": "mxCell",
"attributes": {
"id": "2",
"value": "A",
"style": "",
"vertex": "1",
"parent": "1"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"x": "460",
"y": "80",
"width": "100",
"height": "40",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "3",
"value": "C",
"style": "",
"vertex": "1",
"parent": "1"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"x": "460",
"y": "190",
"width": "100",
"height": "40",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "4",
"edge": "1",
"parent": "1",
"source": "2",
"target": "3"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"relative": "1",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "5",
"value": "B",
"style": "",
"vertex": "1",
"parent": "1"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"x": "280",
"y": "190",
"width": "100",
"height": "40",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "6",
"value": "D",
"style": "",
"vertex": "1",
"parent": "1"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"x": "663",
"y": "193",
"width": "100",
"height": "40",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "7",
"edge": "1",
"parent": "1",
"source": "2",
"target": "5"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"relative": "1",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "8",
"edge": "1",
"parent": "1",
"source": "2",
"target": "6"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"relative": "1",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "9",
"value": "E",
"style": "",
"vertex": "1",
"parent": "1"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"x": "660",
"y": "260",
"width": "100",
"height": "40",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "10",
"edge": "1",
"parent": "1",
"source": "6",
"target": "9"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"relative": "1",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "11",
"value": "F",
"style": "",
"vertex": "1",
"parent": "1"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"x": "280",
"y": "260",
"width": "100",
"height": "40",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "12",
"value": "G",
"style": "",
"vertex": "1",
"parent": "1"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"x": "459",
"y": "257",
"width": "100",
"height": "40",
"as": "geometry"
}
}]
}, {
"tagName": "mxCell",
"attributes": {
"id": "13",
"edge": "1",
"parent": "1",
"source": "11",
"target": "12"
},
"children": [{
"tagName": "mxGeometry",
"attributes": {
"relative": "1",
"as": "geometry"
}
}]
}]
}]
};
graphStateJSON = JSON.stringify(graphState);
}
function html2json(html) {
if (html.nodeType == 3) {
return {
"tagName": "#text",
"content": html.textContent
}
}
var element = {
"tagName": html.tagName
};
if (html.getAttributeNames().length > 0) {
element.attributes = html.getAttributeNames().reduce(
function(acc, at) {
acc[at] = html.getAttribute(at);
return acc;
}, {}
);
}
if (html.childNodes.length > 0) {
element.children = Array.from(html.childNodes)
.filter(
function(el) {
return el.nodeType != 3 ||
el.textContent.trim().length > 0
})
.map(function(el) {
return html2json(el);
});
}
return element;
}
function json2html(json) {
var xmlDoc = document.implementation.createDocument(null, json.tagName);
var addAttributes = function(jsonNode, node) {
if (jsonNode.attributes) {
Object.keys(jsonNode.attributes).map(
function(name) {
node.setAttribute(name, jsonNode.attributes[name]);
}
);
}
}
var addChildren = function(jsonNode, node) {
if (jsonNode.children) {
jsonNode.children.map(
function(jsonChildNode) {
json2htmlNode(jsonChildNode, node);
}
);
}
}
var json2htmlNode = function(jsonNode, parent) {
if (jsonNode.tagName == "#text") {
return xmlDoc.createTextNode(jsonNode.content);
}
var node = xmlDoc.createElement(jsonNode.tagName);
addAttributes(jsonNode, node);
addChildren(jsonNode, node);
parent.appendChild(node);
}
addAttributes(json, xmlDoc.firstElementChild);
addChildren(json, xmlDoc.firstElementChild);
return xmlDoc;
}
</script>
<!-- Loads and initializes the library -->
<script type="text/javascript" src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>
<!-- Example code -->
<script type="text/javascript">
// Program starts here. Creates a sample graph in the
// DOM node with the specified ID. This function is invoked
// from the onLoad event handler of the document (see below).
var graph;
var graphView;
var notConnectedCells = [];
var parentCellId = "2";
function main() {
setGraphData();
// Checks if browser is supported
if (!mxClient.isBrowserSupported()) {
// Displays an error message if the browser is
// not supported.
mxUtils.error('Browser is not supported!', 200, false);
} else {
// Defines an icon for creating new connections in the connection handler.
// This will automatically disable the highlighting of the source vertex.
mxConnectionHandler.prototype.connectImage = new mxImage('images/connector.gif', 16, 16);
// Creates the div for the toolbar
var tbContainer = document.createElement('div');
tbContainer.style.position = 'absolute';
tbContainer.style.overflow = 'hidden';
tbContainer.style.padding = '2px';
tbContainer.style.left = '0px';
tbContainer.style.top = '0px';
tbContainer.style.width = '24px';
tbContainer.style.bottom = '0px';
document.body.appendChild(tbContainer);
// Creates new toolbar without event processing
var toolbar = new mxToolbar(tbContainer);
toolbar.enabled = false
// Creates the div for the graph
var container = document.createElement('div');
container.style.position = 'absolute';
container.style.overflow = 'hidden';
container.style.left = '24px';
container.style.top = '0px';
container.style.right = '0px';
container.style.bottom = '0px';
container.style.background = 'url("editors/images/grid.gif")';
document.body.appendChild(container);
// Workaround for Internet Explorer ignoring certain styles
if (mxClient.IS_QUIRKS) {
document.body.style.overflow = 'hidden';
new mxDivResizer(tbContainer);
new mxDivResizer(container);
}
// Creates the model and the graph inside the container
// using the fastest rendering available on the browser
var model = new mxGraphModel();
graph = new mxGraph(container, model);
// Enables new connections in the graph
graph.setConnectable(true);
graph.setMultigraph(false);
// Stops editing on enter or escape keypress
var keyHandler = new mxKeyHandler(graph);
var rubberband = new mxRubberband(graph);
var addVertex = function(icon, w, h, style) {
var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
vertex.setVertex(true);
var img = addToolbarItem(graph, toolbar, vertex, icon);
img.enabled = true;
graph.getSelectionModel().addListener(mxEvent.CHANGE, function() {
var tmp = graph.isSelectionEmpty();
mxUtils.setOpacity(img, (tmp) ? 100 : 20);
img.enabled = tmp;
});
};
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rectangle.gif', 100, 40, '');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rounded.gif', 100, 40, 'shape=rounded');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/ellipse.gif', 40, 40, 'shape=ellipse');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rhombus.gif', 40, 40, 'shape=rhombus');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/triangle.gif', 40, 40, 'shape=triangle');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/cylinder.gif', 40, 40, 'shape=cylinder');
addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/actor.gif', 30, 40, 'shape=actor');
// read state on load
if (graphStateJSON) {
var doc = json2html(JSON.parse(graphStateJSON));
var dec = new mxCodec(doc);
dec.decode(doc.documentElement, graph.getModel());
}
// save state on change
graph.getModel().addListener('change', function() {
var codec = new mxCodec();
graphStateJSON = JSON.stringify(html2json(codec.encode(
graph.getModel()
)));
});
}
}
function addToolbarItem(graph, toolbar, prototype, image) {
// Function that is executed when the image is dropped on
// the graph. The cell argument points to the cell under
// the mousepointer if there is one.
var funct = function(graph, evt, cell, x, y) {
graph.stopEditing(false);
var vertex = graph.getModel().cloneCell(prototype);
vertex.geometry.x = x;
vertex.geometry.y = y;
graph.addCell(vertex);
graph.setSelectionCell(vertex);
}
// Creates the image which is used as the drag icon (preview)
var img = toolbar.addMode(null, image, function(evt, cell) {
var pt = this.graph.getPointForEvent(evt);
funct(graph, evt, cell, pt.x, pt.y);
});
// Disables dragging if element is disabled. This is a workaround
// for wrong event order in IE. Following is a dummy listener that
// is invoked as the last listener in IE.
mxEvent.addListener(img, 'mousedown', function(evt) {
// do nothing
});
// This listener is always called first before any other listener
// in all browsers.
mxEvent.addListener(img, 'mousedown', function(evt) {
if (img.enabled == false) {
mxEvent.consume(evt);
}
});
mxUtils.makeDraggable(img, graph, funct);
return img;
}
function Validate(mxCell){
let isConnected = true;
// check each cell that each edge connected to
for(let i=0;i<mxCell.getEdgeCount();i++){
let edge = mxCell.getEdgeAt(i);
if(edge.target === null) continue; // no target
if(mxCell.getId() === edge.target.getId()) continue; // target is mxCell itself
isConnected = edge.source !== null && edge.target !== null;
if(isConnected){
// remove source cell if found and so on
let sourceIndex = notConnectedCells.findIndex(c=>c.id === edge.source.getId());
if(sourceIndex !== -1) notConnectedCells.splice(sourceIndex,1);
let targetIndex = notConnectedCells.findIndex(c=>c.id === edge.target.getId());
if(targetIndex !== -1) notConnectedCells.splice(targetIndex,1);
let edgeIndex = notConnectedCells.findIndex(c=>c.id === edge.getId());
if(edgeIndex !== -1) notConnectedCells.splice(edgeIndex,1);
// check next cell and its edges
Validate(edge.target);
}
}
}
function ResetColor(state){
state.shape.node.classList.remove("not_connected");
if(state.text)
state.text.node.classList.remove("not_connected");
}
function SetNotConnectedColor(state){
for(let i=0;i<notConnectedCells.length;i++){
let mxCell = notConnectedCells[i];
let state = graphView.getState(mxCell);
state.shape.node.classList.add("not_connected");
if(state.text)
state.text.node.classList.add("not_connected");
}
}
document.querySelector("#validate_btn").addEventListener("click", function() {
let cells = graph.getModel().cells;
graphView = graph.getView();
notConnectedCells.length = 0;
// create an array of cells and reset the color
for(let key in cells){
if(!cells.hasOwnProperty(key)) continue;
let mxCell = cells[key];
if(!mxCell.isVertex() && !mxCell.isEdge()) continue;
notConnectedCells.push(mxCell);
let state = graphView.getState(mxCell);
ResetColor(state);
}
// starts with the parent cell
let parentCell = notConnectedCells.find(c=>c.id === parentCellId);
Validate(parentCell);
SetNotConnectedColor();
})
</script>
First, set graph to a global variable. (var graph = new mxGraph(container, model);)
Then, get all cells(as an object) and graphView from graph and iterate all the cells checking if it's connected or not.
function Validate(){
let cells = graph.getModel().cells;
let graphView = graph.getView();
for(let key in cells){
if(!cells.hasOwnProperty(key)) continue;
let mxCell = cells[key];
if(!mxCell.isVertex() && !mxCell.isEdge()) continue;
let state = graphView.getState(mxCell);
ResetColor(state);
let notConnected = true;
if(mxCell.isVertex()){
for(let i=0;i<mxCell.getEdgeCount();i++){
let edge = mxCell.getEdgeAt(i);
// if any of an edge connected to both source and target, it's connected
if(edge.source !== null && edge.target !== null){
notConnected = false;
break;
}
}
}
else { // mxCell.isEdge()
notConnected = mxCell.source === null || mxCell.target === null;
}
if(notConnected) SetNotConnectedColor(state);
}
}
function ResetColor(state){
state.shape.node.classList.remove("not_connected");
if(state.text)
state.text.node.classList.remove("not_connected");
}
function SetNotConnectedColor(state){
state.shape.node.classList.add("not_connected");
if(state.text)
state.text.node.classList.add("not_connected");
}
document.querySelector("#validate_btn").addEventListener("click", function(){
Validate();
})
And here's the localStorage version code if you want(codepen)

show tooltip for each point of highcharts network graph in Angular

I am building networkgraphs using highcharts and highcharts-angular on my Angular application. I am able to display the graph with datalabels successfully. Now, I have to show some tooltip data when I hover on each point/node of the graph. How can I do it? How can I show a tooltip corresponding to each point of the graph?
As of now, I am using the below options to draw the graph and show the tooltip. This tooltip, is showing same information when I hover any point. I need to show a different data for each point. How can I do it?
chartOptions = {
"chart": {
"type": "networkgraph",
"height": "100%"
},
"title": {
"text": "Network graph demo"
},
"subtitle": {
"text": "A Force-Directed Network Graph in Highcharts"
},
"plotOptions": {
"networkgraph": {
"keys": ["from", "to"],
"layoutAlgorithm": {
"enableSimulation":true
}
}
},
"series": [
{
"dataLabels": {
"enabled": true,
"linkFormat": ""
},
"data": [{"from" : "a", "to": "b"},
{"from": "a", "to": "c"},
{"from": "a", "to": "d"} ],
"marker" : {"radius" : 18}
}
],
"tooltip" :
{
"enabled" : true,
"formatter" : function() {
return "<div> <span> My tooltip information </span> </div>"
}
}
}
I use console.log() to explore the objects available to me within the Highcharts API
You'll see in the console output all the accessible information, within which name seems to be what you're after?
Try this:
"tooltip" :
{
"enabled" : true,
"formatter" : function() {
console.log(this.point)
return this.point.name
}
}
Update below, is this close to what you're after?
"tooltip" :
{
"enabled" : true,
"useHTML" : true,
"formatter" : function() {
let linkFrom_li = '';
let linkTo_li = '';
let tooltipHTML = '';
for (let i = 0; i < this.point.linksTo.length; i++) {
linkFrom_li = linkFrom_li + `<li>${this.point.linksTo[i].from}</li>`;
}
for (let i = 0; i < this.point.linksFrom.length; i++) {
linkTo_li = linkTo_li + `<li>${this.point.linksFrom[i].to}</li>`;
}
tooltipHTML = tooltipHTML + `<b>Links from [${this.point.name}]</b>:<ul>${linkFrom_li}</ul>`;
tooltipHTML = tooltipHTML + `<b>Links to [${this.point.name}]</b>:<ul>${linkTo_li}</ul>`;
return tooltipHTML;
}
}

tooltip to hide the data based on user selection

I am working on angularjs googlecharts. when user click on legend, corresponding data on the chart is hidden. Issue is with the tooltip. When user click on legend Laptop(blue color) and mouseover on the any of the bar in the chart,the data on the tooltip which shows Laptop should be hidden, but the tooltip is showing information of Laptop also. The same is working when user click on Desktop Legend and mouseover on the bar, the data on the tooltip which shows Desktop is hidden.
Could not able to trace the issue, any suggestion on how to hide the tooltip information displaying Laptop information when user selects the Legend Laptop to hide laptop information.
Please find the demo here
js code:
angular.module('myApp', ['googlechart'])
.controller('myController', function($scope) {
var colorIndex = 0,
chart1 = {};
chart1.type = "ColumnChart";
chart1.displayed = false;
chart1.data = {
"cols": [{
id: "month",
label: "Month",
type: "string"
}, {
id: "laptop-id",
label: "Laptop",
type: "number",
colorIndex: colorIndex++
}, {
role: "tooltip",
type: "string",
p: {
'html': true
}
}, {
id: "desktop-id",
label: "Desktop",
type: "number",
colorIndex: colorIndex++
}],
"rows": [ {
c: [{
v: "Jan"
}, {
v: 13
},{
v: "laptop tooltip bar1"
}, {
v: 1,
f: "1 unit (Out of stock this month)"
}]
} ,{
c: [{
v: "February"
}, {
v: 13
},{
v: "laptop tooltip bar2"
}, {
v: 1,
f: "1 unit (Out of stock this month)"
}]
}, {
c: [{
v: "March"
}, {
v: 24
},{
v: "laptop tooltip bar3"
}, {
v: 5
}]
}]
};
chart1.options = {
"title": "Sales per month",
"colors": ['#0000FF', '#009900'],
"defaultColors": ['#0000FF', '#009900'],
focusTarget: 'category',
"isStacked": "true",
"fill": 20,
"displayExactValues": true,
tooltip: {textStyle: {fontName: '"Arial"', bold: "true", fontSize: "14"}},
"vAxis": {
"title": "Sales unit",
"gridlines": {
"count": 10
}
},
"hAxis": {
"title": "Date"
}
};
chart1.view = {
columns: [0, 1, 2,3]
};
$scope.myChart = chart1;
var hidden = [];
$scope.reset = function() {
for (var i = 0; i < hidden.length; i++) {
var hiddenCol = hidden[i];
$scope.myChart.view.columns[hiddenCol] = hiddenCol;
$scope.myChart.options.colors[hiddenCol - 1] = $scope.myChart.options.defaultColors[hiddenCol - 1];
}
hidden = [];
};
$scope.seriesSelected = function(selectedItem) {
if (selectedItem.row === null) {
var col = selectedItem.column,
colIndex = hidden.indexOf(col),
colorIndex = chart1.data.cols[col].colorIndex;
if (hidden.length === ($scope.myChart.view.columns.length - 3) && colIndex == -1) {
window.alert("One seies of data should be available all time");
}
else{
if(colIndex == -1){
hidden.push(col);
}
else{
hidden.splice(colIndex, 1);
}
if ($scope.myChart.view.columns[col] == col) {
$scope.myChart.view.columns[col] = $scope.myChart.data.cols[col];
$scope.myChart.options.colors[colorIndex] = '#CCCCCC';
}
else {
$scope.myChart.view.columns[col] = col;
$scope.myChart.options.colors[colorIndex] = $scope.myChart.options.defaultColors[colorIndex];
}
}
}
};
});

How to create a new div dynamically everytime a element in data is introduced

I have a data coming from a VM that has several block devices. Every block device is represented with a a line charts that where created using c3.js that read Bytes_Read and Bytes_Written in the dataset and chart it in realtime. But I am struggling with the issue when there are new block devices introduced in dataset it does not create a new chart. What would be the best way to achieve this using JavaScript.
Sample of my dataset
{
"devices": [
{
"Name": "bdev0",
"output": {
"IO_Operations": 0,
"Bytes_Read": 0,
"Bytes_Written": 0
}
},
{
"Name": "bdev0",
"output": {
"IO_Operations": 1,
"Bytes_Read": 2,
"Bytes_Written": 3
}
},
{
"Name": "bdev0",
"output": {
"IO_Operations": 5,
"Bytes_Read": 7,
"Bytes_Written": 8
}
},
{
"Name": "bdev1",
"output": {
"IO_Operations": 10,
"Bytes_Read": 20,
"Bytes_Written": 30
}
}
]
}
Updated dataset with a new device
{
"devices": [
{
"Name": "bdev0",
"output": {
"IO_Operations": 0,
"Bytes_Read": 0,
"Bytes_Written": 0
}
},
{
"Name": "bdev0",
"output": {
"IO_Operations": 1,
"Bytes_Read": 2,
"Bytes_Written": 3
}
},
{
"Name": "bdev0",
"output": {
"IO_Operations": 5,
"Bytes_Read": 7,
"Bytes_Written": 8
}
},
{
"Name": "bdev1",
"output": {
"IO_Operations": 10,
"Bytes_Read": 20,
"Bytes_Written": 30
},
{
"Name": "bdev2",
"output": {
"IO_Operations": 40,
"Bytes_Read": 50,
"Bytes_Written": 90
}
}
]
}
chart code
eon.chart({
pubnub : pubnub,
history : false,
channel : 'orbit5_volume',
flow : true,
debug: true,
generate : {
bindto : '#chart',
size: {
height: 180,
width: 500
},
data : {
x : 'x',
labels : true
},
axis : {
x : {
type : 'timeseries',
tick : {
format : '%H:%M:%S'
},
zoom: {
enabled: true
}
}
}
},
transform : function(m) {
for (var i in m.devices){
return { columns : [
['x', new Date().getTime()],
['Bytes Written', m.devices[i].output.Bytes_Read],
['Bytes Read', m.devices[i].output.Bytes_Written]
]
}
}
}
});
You're chart code transform loop is overwriting every data's key which is why you're only getting a couple values. If you use the i variable to give each piece of data a new key, it'll show up on the chart.
Try this transform function:
eon.chart({
transform : function(m) {
var obj = {columns: [
['x', new Date().getTime()]
]};
for (var i in m.devices) {
obj.columns.push(['Bytes Read ' + i, m.devices[i].output.Bytes_Read]);
obj.columns.push(['Bytes Written ' + i, m.devices[i].output.Bytes_Written]]);
}
}
return obj;
}
});

Delete certain parts of json array

I'd like to create a new JSON array based on certain values.
Sample JSON:
var array =
{
"entries": {
"houses": [
{
"category": {
"category_id":"1",
"category_foo":"bar",
},
"important": {
"important_foo":"bar",
"dontforget":"me",
}
},
{
"category": {
"category_id":"1",
"category_foo":"bar",
},
"important": {
"important_foo":"bar",
"dontforget":"me",
}
},
"category": {
"category_id":"2",
"category_foo":"bar",
},
"important": {
"important_foo":"bar",
"dontforget":"me",
}
}
]
}
}
Now I need a way to search through this array and create a new array with all houses that have a category with category_id=1. Of course it should keep all the rest of the infos like important.
The new array should look like:
{
"entries": {
"houses": [
{
"category": {
"category_id":"1",
"category_foo":"bar",
},
"important": {
"important_foo":"bar",
"dontforget":"me",
}
},
{
"category": {
"category_id":"1",
"category_foo":"bar",
},
"important": {
"important_foo":"bar",
"dontforget":"me",
}
}
]
}
}
Any help is appreciated!
You can use Array.filter to do this:
var filteredResults = array.entries.houses.filter(function(house) {
return house.category && house.category_id == 1;
});
This code works.
var houses = array.entries.houses;
var newHouses = [];
for (var i = 0; i < houses.length; i++)
{
if (houses[i].category.category_id == "1") {
newHouses.push(houses[i]);
}
}
Check this out: https://jsfiddle.net/2u13phw3/

Categories

Resources