如何在Cytoscape.js中制作加权图?

问题描述

我是cytoscape的新手,我已经阅读了文档,但找不到有帮助的东西。有没有办法在Cytoscape.js中制作类似这样的东西(加权图)?:

enter image description here

我只需要知道如何显示边缘的重量。

到目前为止,我有这个:

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" },],

但是向边缘添加权重不会在图形中显示权重:

enter image description here

解决方法

您可以在CSS中为边缘使用'label': 'data(weight)',以将weight属性显示为边缘的标签。您还可以根据详细here来调整此标签的样式。我在以下示例中应用了其中两个(text-margin-y和text-orientation)。

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>