vis-network中文文档 - 入门

3,924 阅读2分钟

原文

Network(关系图)

关系网是由节点和边组成,关系网易于使用,支持自定义形状、样式、颜色、大小、图像等。关系网在任何现代浏览器上都能顺畅的工作,最多可支持几千个节点。

从4.0开始,关系网由处理关系图特定部分的各个模块组成。每个模块都有独立的说明文档,通过单击下面列表中的模块可以访问模块的选项、方法和事件。

创建Network

你很容易创建一个关系网(network实例)。但是在创建之前请正确引入vis.jscss文件。

  • Standalone build:
    • simple to use (link/require/import a single file),
    • CSS included and automatically injected into the page,
    • JavaScript dependencies bundled,
    • doesn't work with other Vis family packages,
    • example usage,
    • linkable files on unpkg.
  • Peer build:
    • in case of UMD Vis Data and Vis Util have to be loaded manually,
    • in case of ESM DataSets, DataViews etc. have to be loaded from Vis Data,
    • CSS has to be included separately,
    • works with other Vis family packages,
    • example usage,
    • linkable files on unpkg.
  • Legacy build:
    • kept only for backward compatibility, please don't use,
    • contains Moment which is not used by Vis Network (aka bloatware),
    • CSS has to be included sepparately,
    • JavaScript dependencies bundled,
    • doesn't play well with tree shaking,
    • doesn't work with other Vis family packages,
    • example usage,
    • linkable files on unpkg.

当你引入这些文件后还需要指定节点和边数据。

当然你也可以使用DOT语言或从Gephi导出节点和边数据,但在教程中我们暂不涉及这些。

您还可以使用vis.Datasets进行动态数据绑定,例如,在初始化网络后更改颜色、标签或任何选项。

一旦你有了数据,你所需要的就是一个容器div来告诉vis把你的关系网放到哪里。此外,还可以使用选项对象来自定义关系网。

简单示例(使用standalone build方式):

See the Pen <a href='https://codepen.io/liufeipeng/pen/ExPVGRE'>Vis Network | Basic usage</a> by liufeipeng (<a href='https://codepen.io/liufeipeng'>@liufeipeng</a>) on <a href='https://codepen.io'>CodePen</a>.
//源码
<html>
<head>
    <script type="text/javascript" src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>

    <style type="text/css">
        #mynetwork {
            width: 600px;
            height: 400px;
            border: 1px solid lightgray;
        }
    </style>
</head>
<body>
<div id="mynetwork"></div>

<script type="text/javascript">
    // 创建节点数据数组
    var nodes = new vis.DataSet([
        { id: 1, label: "Node 1" },
        { id: 2, label: "Node 2" },
        { id: 3, label: "Node 3" },
        { id: 4, label: "Node 4" },
        { id: 5, label: "Node 5" }
    ]);

    // 创建边数据数组
    var edges = new vis.DataSet([
        { from: 1, to: 3 },
        { from: 1, to: 2 },
        { from: 2, to: 4 },
        { from: 2, to: 5 },
        { from: 3, to: 3 }
    ]);

    // 获取容器
    var container = document.getElementById('mynetwork');

    // 将数据赋值给vis 数据格式化器
    var data = {
        nodes: nodes,
        edges: edges
    };
    var options = {};

    // 初始化关系图
    var network = new vis.Network(container, data, options);
</script>
</body>
</html>