Search code examples
javascriptgraph-theorycytoscape.jscytoscape

How to make a weighted graph in Cytoscape.js?


Im new to cytoscape, I have read the docs but can't find something that helps. Is there a way to make something like this (a weighted graph) in Cytoscape.js?:

enter image description here

I just need to know how to display the weight of the edge.

So far I have this:

elements: [
  // list of graph elements to start with
  {
    // node a
    data: { id: "a" },
  },
  {
    // node b
    data: { id: "b" },
  },
  {
    // edge ab
    data: { id: "ab", weight: 3, source: "a", target: "b" },
  },
],

But adding a weight to the edge doesn't display the weight in the graph: enter image description here


Solution

  • You can use 'label': 'data(weight)' in your css for the edge to show the weight property as a label of the edge. You can also adjust styling of this label as detailed here. I applied two of them (text-margin-y and text-orientation) in the below sample.

    var cy = window.cy = cytoscape({
      container: document.getElementById('cy'),
      layout: {name: 'grid', rows: 2},
      style: [{
          selector: 'node',
          css: {
            'content': 'data(id)',
            'text-valign': 'center',
            'text-halign': 'center'
          }
        },
        {
          selector: 'edge',
          css: {
            'label': 'data(weight)',
            'text-margin-y': 15,
            'text-rotation': 'autorotate'
          }
        }
      ],
      elements: {
        nodes: [{
            data: {
              id: 'n0'          
            }
          },
          {
            data: {
              id: 'n1'
            }
          },
          {
            data: {
              id: 'n2'
            }
          },
          {
            data: {
              id: 'n3'
            }
          }
        ],
        edges: [{
            data: {
              id: 'n0n1',
              source: 'n0',
              target: 'n1',
              weight: 3
            }
          },
          {
            data: {
              id: 'n1n2',        
              source: 'n1',
              target: 'n2',
              weight: 5
            }
          },
          {
            data: {
              id: 'n2n3',        
              source: 'n2',
              target: 'n3',
              weight: 7
            }
          }
        ]
      }
    });
    body {
      font: 14px helvetica neue, helvetica, arial, sans-serif;
    }
    
    #cy {
      height: 95%;
      width: 95%;
      left: 0;
      top: 0;
      position: absolute;
    }
    <html>
    
    <head>
      <meta charset=utf-8 />
      <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
      <script src="https://unpkg.com/cytoscape@3.10.0/dist/cytoscape.min.js">
      </script>
    </head>
    
    <body>
      <div id="cy"></div>
    </body>
    
    </html>