Create 2D Spherical Network Graph
by Rajesh Danabal
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2D Spherical Network Graph with Cytoscape</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cytoscape.min.js"></script>
<style>
#cy {
width: 100%;
height: 100vh;
display: block;
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div id="cy"></div>
<script>
// Create a Cytoscape instance
const cy = cytoscape({
container: document.getElementById('cy'),
elements: [
{ data: { id: 'a' } },
{ data: { id: 'b' } },
{ data: { id: 'c' } },
{ data: { id: 'd' } },
{ data: { id: 'e' } },
{ data: { id: 'f' } },
{ data: { id: 'g' } },
{ data: { id: 'h' } },
{ data: { id: 'i' } },
{ data: { id: 'j' } },
{ data: { id: 'k' } }
],
style: [
{
selector: 'node',
style: {
'background-color': '#0074d9',
'label': 'data(id)',
'width': 30,
'height': 30
}
},
{
selector: 'edge',
style: {
'width': 2,
'line-color': '#ccc',
'opacity': 0.5
}
}
],
layout: {
name: 'circle',
padding: 10,
}
});
const numNodes = cy.nodes().length;
const radius = 200; // Radius of the virtual sphere
const phiStep = Math.PI / Math.sqrt(numNodes); // Step for latitude (phi)
const thetaStep = 2 * Math.PI / numNodes; // Step for longitude (theta)
// Calculate spherical positions and project into 2D
cy.nodes().forEach((node, i) => {
const phi = i * phiStep; // Latitude angle
const theta = (i % numNodes) * thetaStep; // Longitude angle
// Spherical to Cartesian projection
const x = cy.width() / 2 + Math.sin(phi) * Math.cos(theta) * radius;
const y = cy.height() / 2 + Math.sin(phi) * Math.sin(theta) * radius;
// Set node...