图论与网络模型——基于R

图的定义

从直观上看,所谓图就是由点与边组成的图形,如下图所示:
在这里插入图片描述

定义:图G是一个偶对(V,E),其中V是一个非空集合,其元素u属于V称为图的定点;E是由V中的点构成的点对,E的元素e称为图的变或弧。若e是无序对,则称G为无向图,否则则成为有向图。若e=(u,v),则称u为e的起点,v为e的终点。称去掉有向图的方向得到的图为基础图

构建图中的R函数

在igraph中可用graph函数构件图,其使用格式为:

make_graph(
  edges,
  ...,
  n = max(edges),
  isolates = NULL,
  directed = TRUE,
  dir = directed,
  simplify = TRUE
)

make_directed_graph(edges, n = max(edges))

make_undirected_graph(edges, n = max(edges))

directed_graph(...)

undirected_graph(...)
Arguments

其中:

  • edges为由顶点符号构成的向量,表示图的边,其中奇数点表示边的起点,偶数点表示终点
  • n 为整数,默认值为最大边数
  • directed为逻辑变量,表示是否为有向图
    graph函数返回值为图的对象,如果将图可视化,需要用到plot函数
    比如我们这两幅图:
#install.packages("igraph")
library(igraph)
e=c(1,2,2,2,2,4,1,4,3,1,3,4,4,3,4,5)
par(mfrow=c(1,2))#把图形分割为两部分
enames <- paste("e",1:8,sep="")
g1 <- graph(e,directed = F)
g2 <- graph(e)
plot(g1,layout=layout.circle,edge.label=enames)
plot(g2,layout=layout.circle,edge.label=enames)

在这里插入图片描述

  • edge.label=enames表示绘图时表明边的标号
  • layout=layout.circle表明图中顶点的布局类似于一个圆

把无向图变为有向图

如图所示,把左边的这个图变成右边:

as.directed(graph,mode=c("mutual","arbitrary","each","random"))
  • 参数graph为作图的对象,mode为字符串。取“mutual”(默认值)表示为木条边增加两个方向,取“arbitrary”表示为每条边任意添加一个方向
library(tidyverse)
plot(g1,layout=layout.circle,edge.label=enames)#无向图
as.directed(g1,mode="mutual") %>% plot(layout=layout.circle,edge.label=enames)

在这里插入图片描述

构建空图

graph.empty函数

graph.empty(n=0,directed = T) %>% plot()

结果如下:
在这里插入图片描述

在图上添加边或者点

  • add.edges(): 添加边
  • add.vertices(): 添加点
    例题
    使用igraph的函数构建图,图G共有10个顶点,顶点用小写英文字母表示,共20条边,边的连接方式如下:
    1,2,1,3,2,3,3,5,3,4,3,6,3,7,4,5,4,9,5,1,5,6,7,1,7,8,
    8,2,8,5,8,9,9,5,9,10,10,6
E <- c(1,2,1,3,2,3,3,5,3,4,3,6,3,7,4,5,4,9,5,1,5,6,7,1,7,8,
       8,2,8,5,8,9,9,5,9,10,10,6)
g3 <- graph.empty()+vertices(letters[1:10])
g3 <-g3+ edges(E) 
plot(g3,layout=layout.circle)

在这里插入图片描述

简单图与完全图

用到graph.fromula函数
graph.full()函数
graph.ring()函数

graph.formula(A-+B-+C) %>% plot()
graph.formula(A+-B-+C) %>% plot()
graph.formula(A+-B--C) %>% plot()

在这里插入图片描述
在这里插入图片描述

graph.lattice(c(2,2,2)) %>% plot()
graph.full(5) %>% plot()
graph.ring(10) %>% plot()

在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值