【React】Sigma.js框架网络图-入门篇

news/2024/5/19 15:16:48

一、介绍

Sigma.js是一个专门用于图形绘制的JavaScript库 它使在Web页面上发布网络变得容易,并允许开发人员将网络探索集成到丰富的Web应用程序中。
Sigma.js提供了许多内置功能,例如CanvasWebGL渲染器或鼠标和触摸支持,以使用户在网页上的网络操作流畅且快速。
通过使用Sigma.js,用户可以方便地创建和展示网络图,从而更好地理解和分析数据之间的关系。

在这里插入图片描述

二、实战

1、环境&目录结构

在这里插入图片描述

  • Next.js初始化
# npx create-next-app@latest
# ...
√ What is your project named? ... graph-sigma
√ Would you like to use TypeScript? ... Yes
√ Would you like to use ESLint? ... No
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? (recommended) ... Yes
√ Would you like to customize the default import alias (@/*)? ... Yes
√ What import alias would you like configured? ... @/*
  • sigma.js安装

需要安装两个核心库:sigmagraphology

  • Sigma: 它支持多种布局算法,并允许用户通过鼠标和触摸来交互网络。提供丰富的API和配置选项,使得网络图的绘制和定制变得相对简单。
  • Graphology 是一个简单、高效且灵活的图形数据结构库,它支持节点和边的添加、删除和查询操作,并提供了许多用于分析图形结构的实用方法。GraphologySigma.js 常常一起使用,因为 Sigma.js 可以使用 Graphology 作为其后端图形数据结构。
npm install sigma graphology
  • package.json配置
"dependencies": {"graphology": "^0.25.4","next": "14.2.2","react": "^18","react-dom": "^18","sigma": "^3.0.0-beta.17"
}

2、sigma组件使用示例

在这里插入图片描述

import type {Node, Edge} from "@/component/SigmaGraph/types.d";import SigmaGraph from "@/component/SigmaGraph";
import SigmaGraphData from "@/component/SigmaGraph/SigmaGraphData";export default function Home() {// 示例:节点 数据const nodes:Node[] = [{id: "1", label: "Node 1", x: 0, y: 0, size: 10, color: "blue" },{id: "2", label: "Node 2", x: 1, y: 1, size: 20, color: "red" },];// 示例:边 数据const edges:Edge[] = [{source: "1", target: "2", size: 5, color: "purple"}];return (<div style={{width: '50vw', height: '50vh', backgroundColor: "#eee"}}><SigmaGraph><SigmaGraphData nodes={nodes} edges={edges}/></SigmaGraph></div>);
}

3、创建sigma组件

next.js中,切记sigma.js的一切代码只能在客户端模式下进行

在根目录的component目录创建一个SigmaGraph目录和其他准备文件
在这里插入图片描述

  • types.d.ts声明文件
// 节点(Node)、边(Edge)数据结构声明
export type Node = {id: string,[key: string]: any
}export type Edge = {source: string,target: string,[key: string]: any
}
  • index.tsx父组件
"use client";import type {Attributes} from "graphology-types";
import type {Settings} from "sigma/settings";import React, {useEffect, useRef, useState, createContext, useContext, useMemo} from "react";
import Graph from "graphology";
import Sigma from "sigma";// 声明组件可传参数
type SigmaGraphProps = {children?: React.ReactNode,settings?: Partial<Settings>
}// 创建 SigmaGraph 上下文
export const SigmaGraphContext = createContext<Sigma<Attributes, Attributes, Attributes>|null>(null);// 定义div容器基本样式(一定要有宽高设定)
const containerStyle: React.CSSProperties = {width: '100%',height: '100%'
}let graph: Graph | null = new Graph;const SigmaGraph = function ({children, settings}: SigmaGraphProps) {const containerRef = useRef<HTMLDivElement>(null);const [sigma, setSigma] = useState<any>(null);// 默认配置const sigmaSettings: Partial<Settings> = useMemo(() => (Object.assign({}, {allowInvalidContainer: true,}, settings || {})), [settings])//useEffect(() => {if (typeof window !== 'undefined' && containerRef.current) {const sigmaInstance = new Sigma(graph, containerRef.current, sigmaSettings);// 为上下文操作准备 graph 和 sigma 实例setSigma(sigmaInstance);}}, []);//return (<SigmaGraphContext.Provider value={sigma}><div ref={containerRef} style={containerStyle}>{children}</div></SigmaGraphContext.Provider>)
}// 导出 sigma hook
export const useSigma = () => useContext(SigmaGraphContext);// 导出 graph hook
export const useGraph = () => graph;export default SigmaGraph;
  • SigmaGraphData.tsx子组件:用于数据更新、维护
"use client";import type {Node, Edge} from "./types.d";import {useSigma, useGraph} from "./index"
import React, {useEffect} from "react";// 声明组件可传参数
type SigmaDataProps = {nodes: Node[],edges: Edge[],
}const SigmaGraphData = function ({nodes, edges}:SigmaDataProps) {// 挂载 sigma、graphconst sigma = useSigma();const graph = useGraph();useEffect(() => {if (!sigma || !graph)return;// 清空原有数据graph.clear();// 添加 节点 数据nodes.forEach((node: Node)=>{graph.addNode(node.id, node);});// 添加 边 数据(也就是节点之间的关系)edges.forEach((edge: Edge)=>{graph.addEdge(edge.source, edge.target, edge);});sigma.refresh();// 组件销毁时 清空return () => graph.clear();}, [graph,sigma, nodes, edges]);return <></>
}export default SigmaGraphData;

三、实际执行流程

上面看着是不是好像挺复杂,其实只做了以下几个事情:

  • 假定容器
<div id="graphContainer"></div>
  • 模拟数据
// 示例:节点 数据
const nodes = [{ id: "1", label: "Node 1", x: 0, y: 0, size: 10, color: "blue" },{ id: "2", label: "Node 2", x: 1, y: 1, size: 20, color: "red" },
];
// 示例:边 数据
const edges = [{ source: "1", target: "2", size: 5, color: "purple" },
];
  • 视图渲染
import Graph from "graphology";
import Sigma from "sigma";const graphContainer = document.getElementById('graphContainer')// 设置默认 sigma 库配置
const sigmaSettings = {};// 实例化 Graph 库(既Graphology图形数据结构库)
const graphInstance = new Graph();// 添加 节点 数据
nodes.forEach((node)=>{graphInstance.addNode(node.id, node);
});// 添加 边 数据(也就是节点之间的关系)
edges.forEach((edge)=>{graphInstance.addEdge(edge.source, edge.target, edge);
});// 实例化 Sigma 库,传入<graph、HTML元素、默认配置>
const sigmaInstance = new Sigma(graph, graphContainer, sigmaSettings);

http://www.mrgr.cn/p/33135772

相关文章

改善员工绩效管理的 8 种最佳方法

企业如何改进绩效管理体系,才能获得最好的结果?请仔细阅读,找出答案… 人力资源部门对组织的成功起着至关重要的作用,组织的员工也是如此。更好的组织管理会带来更高的利润。人力资源部门的工作很大一部分就是规范绩效管理体系,营造员工能做出最好的工作、发挥最大能力的工…

【数据结构】时间复杂度的例题

&#x1f381;个人主页&#xff1a;我们的五年 &#x1f50d;系列专栏&#xff1a;数据结构 &#x1f337;追光的人&#xff0c;终会万丈光芒 目录 &#x1f337;例题1&#xff1a; &#x1f337;例题2&#xff1a; &#x1f337;例题3&#xff1a; &#x1f337;例题4&am…

amCharts图像分类

代码案例<!DOCTYPE html> <html><head><script src="https://cdn.amcharts.com/lib/5/index.js"></script><script src="https://cdn.amcharts.com/lib/5/xy.js"></script><script src="https://cdn.am…

车用MCU,R7F701320EAFP、R7F701321EAFP、R7F701322EAFP、R7F701323EAFP微控制器功耗低,闪存容量高达2MB

RH850/P1M 是适用于底盘系统的汽车微控制器,功耗低,闪存容量高达 2 MB,RAM 容量高达 128 KB。RH850/P1M——适用于底盘系统的汽车用微控制器 简介 RH850/P1M 微控制器功耗低,闪存容量高达 2 MB,RAM 容量高达 128 KB,具有增强型电机控制定时器、CAN 接口、SENT 和 PSI5 等…

Recommended Azure Monitors

General This document describes the recommended Azure monitors which can be implemented in Azure cloud application subscriptions. SMT incident priority mapping The priority “Blocker” is mostly used by Developers to prioritize their tasks and its not a…

主打熟人双向社交,UXLINK 如何用群组打造超强社交生态

社交&#xff0c;作为最强 Web3 流量入口 Web2 世界里&#xff0c;社交产品总是最具想象力。全球使用 Facebook 系列产品的日活用户&#xff08;DAP&#xff09;均值近 30 亿人&#xff0c;占全球人口的 1/3。然而&#xff0c;加密货币用户仅约有 4.2 亿&#xff0c;占全球人口…

Apache RocketMQ ACL 2.0 全新升级

我们推出了 RocketMQ ACL 2.0 升级版,进一步提升 RocketMQ 数据的安全性。本文将介绍 RocketMQ ACL 2.0 的新特性、工作原理,以及相关的配置和实践。作者:徒钟 引言 RocketMQ 作为一款流行的分布式消息中间件,被广泛应用于各种大型分布式系统和微服务中,承担着异步通信、系…

说说你对分而治之、动态规划的理解?区别?

一、分而治之 分而治之是算法设计中的一种方法,就是把一个复杂的问题分成两个或更多的相同或相似的子问题,直到最后子问题可以简单的直接求解,原问题的解即子问题的解的合并 关于分而治之的实现,都会经历三个步骤:分解:将原问题分解为若干个规模较小,相对独立,与原问题…

【C语言】深入解析选择排序算法

一、算法原理二、算法性能分析三、C语言实现示例四、总结 一、算法原理 选择排序&#xff08;Selection Sort&#xff09;是一种简单直观的排序算法。它的工作原理是不断地选择剩余元素中的最小&#xff08;或最大&#xff09;元素&#xff0c;放到已排序的序列的末尾&#xff…

科普:嵌入式代码软件在环(SiL)测试的可靠性

​​关键词:嵌入式系统、软件在环(SiL)、测试、生命周期01.简介当前,嵌入式系统开发的大趋势为通过软件实现大量的硬件功能,这导致软件的复杂程度显著上升——代码开发成本和风险也成倍增加。复用已有系统中的软件组件是改进嵌入式系统生命周期的一种可能的解决方案,对代…

hitcontraining_heapcreator

[BUUCTF]hitcontraining_heapcreator UAF|Off-By-One|堆溢出 对应libc版本libc6_2.23-0ubuntu9_amd64 [*] /home/bamuwe/heapcreator/heapcreatorArch: amd64-64-littleRELRO: Partial RELROStack: Canary foundNX: NX enabledPIE: No PIE (0x3fc000)bamu…

django自定义构建模板,通过bootstrap实现菜单隐藏和显示

实现后的界面1.自定义页面模板实现 主页面代码(home.html) {% extends layout.html %} #引用模板 {% load static %} {% block content %}<h3>欢迎登录</h3> {% endblock %}自定义内容layout.html文件设置(模板){% load static %} {% load menu %} #导入me…

五一~感恩回馈,SolidKits工具折扣来袭!

SOLIDWORKS插件多样且丰富,有着不同的种类和用途,可以为SOLIDWORKS软件本身提升使用效率,更快速的响应你的操作方式。SolidKits自主设计研发多款SOLIDWORKS增效插件,包括:自动化参数设计插件、高级BOM插件、批量编码器插件、标准件增强工具等,也可提供按需定制开发服务。…

蓝桥杯2024年第十五届省赛真题-握手问题

方法一&#xff1a;模拟 #include<bits/stdc.h> using namespace std; #define int long long const int n1e6; int a,b[n],c; signed main() {for(int i1;i<50;i){for(int ji1;j<50;j){if(i<7&&j<7){continue;}c;}}cout<<c<<endl; }方…

wstunnel (websocket模式ssh)

接上一篇 修改客户端运行参数 ssh -o ProxyCommand"./wstunnel client -L stdio://%h:%p ws://192.168.254.131:8080" 127.0.0.1 其中127.0.0.1为服务端的本地ssh访问&#xff0c;可以修改为通过服务端访问其他设备的ssh服务。例如&#xff1a; ssh -o ProxyComma…

一个java项目中,如何使用sse协议,构造一个chatgpt的流式对话接口

前言 如何注册chatGPT&#xff0c;怎么和它交互&#xff0c;本文就不讲了&#xff1b;因为网上教程一大堆&#xff0c;而且你要使用的话&#xff0c;通常会再包一个算法服务&#xff0c;用来做一些数据训练和过滤处理之类的&#xff0c;业务服务基本不会直接与原生chatGPT交互。…

使用自己云服务器frp内网穿透记录

1.前提是自己现有云服务器已经2.下载对应的版本,我使用的是052.3下载地址 https://github.com/fatedier/frp/releases需要注意:下载的linux版本是服务端。windows是客户端 后续需要修改对用的配置文件 3.解压linux3.1 编辑配置文件vi frps.toml bindPort = 7000 # 服务运行端…

.net6 ILogger日志保存到本地

1、新建一个LocalFileLogger的类public class LocalFileLogger : ILogger{private readonly string categoryName;private readonly string basePath;public LocalFileLogger(string categoryName){this.categoryName = categoryName;string[] fieldstrs = Enum.GetNames(typeo…

CISCN2023-华北-normal_snake

就得审java。 路由分析 老规矩,先看看路由:/read路由下传参data,pyload不能包含!!,然后用了yaml来load传入的参数。 稍作了解,这其实就是 SnakeYaml 反序列化漏洞,禁用了 yaml 的常用头 !!。 前面的!!是用于强制类型转化,强制转换为!!后指定的类型,其实这个和Fastjson的…

如何用Sublime Text实现正则查找与替换

比如将下面的汉字语义加上中括号[{"text": "微笑","path": "emot01.png"},{"text": "大笑","path": "emot02.png"},{"text": "鼓掌","path": "emot03.pn…