R -- 圖形理論 (含搜尋策略)

統計軟體 R

簡介

安裝

操作方式

變數與運算

有序數列

向量

矩陣

多維陣列

複數

因子

串列

資料框

時間數列

流程控制

輸出入

呼叫

函數

2D 繪圖

3D 繪圖

互動介面

套件列表

其他語言呼叫

R 的應用

集合

邏輯推論

模糊邏輯

機率邏輯

檢定

搜尋

優化算法

線性代數

決策樹

人工智慧

分群分類

SVM 向量機

神經網路

遺傳演算法

資料採礦

訊號處理

影像處理

語音處理

自然語言

機器學習

機器人

生物統計

數位訊號處理

方程式求解

數值分析

微積分

微分方程

線性規劃

圖形理論

統計推論

字串處理

正規表示式

視窗程式

網頁程式

文件格式

貝氏網路

訊息

機率統計書

相關網站

參考文獻

最新修改

簡體版

English

  1. http://cran.r-project.org/web/packages/igraph/index.html (iGraph)
  2. http://cran.r-project.org/web/packages/qgraph/index.html (qGraph)
  3. gRaphical Models in R — http://cran.r-project.org/web/views/gR.html

igraph 操作

必須先用 install.packages("igraph") 安裝 igraph 套件,然後再用 library("igraph") 引入套件。

g <- graph( c(0,1, 0,2, 1,2, 2,4), n=5 ) # 失敗.... 由於 igraph 改從 1 開始了,所以不能從 0 開始 ....

g <- graph( c(1,2, 1,3, 2,3, 3,5), n=5 )
g
IGRAPH D--- 5 4 -- 
plot(g)

問題:http://stackoverflow.com/questions/7521381/draw-network-in-r-control-edge-thickness-plus-non-overlapping-edges

I'm not sure why but the bit which has the code g <- graph.edgelist(as.matrix(Edges[,-3]-1)) produces an error like Error in graph(t(el), directed = directed) : At structure_generators.c:84 : Invalid (negative) vertex id, Invalid vertex id any idea what the problem is? – h.l.m Oct 3 '12 at 1:23

解答:

This is because since this answer igraph changed node numbering starting from 1 now where it was 0. It works if you remove the -1. Edited the answer as well. – Sacha Epskamp Oct 3 '12 at 6:06

adj.mat <- matrix(sample(c(0,1), 9, replace=TRUE), nr=3)
g <- graph.adjacency(adj.mat)
plot(g)
# 也可以画出一些特殊结构的图形,例如下面的星形图
g2 <- graph.star(10, mode = "in")
plot(g2,layout=layout.fruchterman.reingold(g2))

# 当然也能从文件创建图形
# 首先读入数据,整理后用graph.data.frame函数创建图形对象
traits <- read.csv('http://igraph.sourceforge.net/igraphbook/traits.csv', head=FALSE)
names(traits) <- c('name','age','gender')
traits[,1] <- sapply(strsplit(as.character(traits[,1]),' '),'[',1)
relation <- read.csv('http://igraph.sourceforge.net/igraphbook/relations.csv', head=FALSE)
names(relation) <- c('from','to','sameroom','friendship','advice')
g4 <- graph.data.frame(relation,vertices=traits)
plot(g4,layout=layout.kamada.kawai,vertex.shape='rectangle',vertex.label=V(g4)$name,vertex.size=20,asp=F)
# Data format. The data is in 'edges' format meaning that each row records a relationship (edge) between two people (vertices).
# Additional attributes can be included. Here is an example:
#    Supervisor    Examiner    Grade    Spec(ialization)
#    AA        BD        6    X    
#    BD        CA        8    Y
#    AA        DE        7    Y
#    ...        ...        ...    ...
# In this anonymized example, we have data on co-supervision with additional information about grades and specialization. 
# It is also possible to have the data in a matrix form (see the igraph documentation for details)

# Load the data. The data needs to be loaded as a table first: 

bsk<-read.table("http://www.dimiter.eu/Data_files/edgesdata3.txt", sep='\t', dec=',', header=T)#specify the path, separator(tab, comma, ...), decimal point symbol, etc.

# Transform the table into the required graph format:
bsk.network<-graph.data.frame(bsk, directed=F) #the 'directed' attribute specifies whether the edges are directed
# or equivelent irrespective of the position (1st vs 2nd column). For directed graphs use 'directed=T'

# Inspect the data:

V(bsk.network) #prints the list of vertices (people)
E(bsk.network) #prints the list of edges (relationships)
degree(bsk.network) #print the number of edges per vertex (relationships per people)

# First try. We can plot the graph right away but the results will usually be unsatisfactory:
plot(bsk.network)

範例 2

#Subset the data. If we want to exclude people who are in the network only tangentially (participate in one or two relationships only)
# we can exclude the by subsetting the graph on the basis of the 'degree':

bad.vs<-V(bsk.network)[degree(bsk.network)<3] #identify those vertices part of less than three edges
bsk.network<-delete.vertices(bsk.network, bad.vs) #exclude them from the graph

# Plot the data.Some details about the graph can be specified in advance.
# For example we can separate some vertices (people) by color:

V(bsk.network)$color<-ifelse(V(bsk.network)$name=='CA', 'blue', 'red') #useful for highlighting certain people. Works by matching the name attribute of the vertex to the one specified in the 'ifelse' expression

# We can also color the connecting edges differently depending on the 'grade': 

E(bsk.network)$color<-ifelse(E(bsk.network)$grade==9, "red", "grey")

# or depending on the different specialization ('spec'):

E(bsk.network)$color<-ifelse(E(bsk.network)$spec=='X', "red", ifelse(E(bsk.network)$spec=='Y', "blue", "grey"))

# Note: the example uses nested ifelse expressions which is in general a bad idea but does the job in this case
# Additional attributes like size can be further specified in an analogous manner, either in advance or when the plot function is called:

V(bsk.network)$size<-degree(bsk.network)/10#here the size of the vertices is specified by the degree of the vertex, so that people supervising more have get proportionally bigger dots. Getting the right scale gets some playing around with the parameters of the scale function (from the 'base' package)

# Note that if the same attribute is specified beforehand and inside the function, the former will be overridden.
# And finally the plot itself:
par(mai=c(0,0,1,0))             #this specifies the size of the margins. the default settings leave too much free space on all sides (if no axes are printed)
plot(bsk.network,                #the graph to be plotted
layout=layout.fruchterman.reingold,    # the layout method. see the igraph documentation for details
main='Organizational network example',    #specifies the title
vertex.label.dist=0.5,            #puts the name labels slightly off the dots
vertex.frame.color='blue',         #the color of the border of the dots 
vertex.label.color='black',        #the color of the name labels
vertex.label.font=2,            #the font of the name labels
vertex.label=V(bsk.network)$name,        #specifies the lables of the vertices. in this case the 'name' attribute is used
vertex.label.cex=1            #specifies the size of the font of the labels. can also be made to vary
)

# Save and export the plot. The plot can be copied as a metafile to the clipboard, or it can be saved as a pdf or png (and other formats).
# For example, we can save it as a png:
png(filename="org_network.png", height=800, width=600) #call the png writer
#run the plot
dev.off() #dont forget to close the device
#And that's the end for now.

qGraph 操作

> Edges <- data.frame(
+     from = rep(1:5,each=5),
+     to = rep(1:5,times=5),
+     thickness = abs(rnorm(25)))
> 
> Edges <- subset(Edges,from!=to)
> library("qgraph")
> qgraph(Edges,esize=5,gray=TRUE)
> qgraph(Edges,esize=5,gray=TRUE,minimum=0,cut=.Machine$double.xmin)
>

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License