EDIT(2017 年 7 月 7 日):
由于我最初回答了这个问题,一个新的和改进的网络/图形绘图包,ggraph
,已经发布,我认为它应该取代下面的选项,所以我正在编辑我的答案以添加ggraph
option:
首先,进行一些操作以获取 igraph 图形对象的顶点和边:
library(igraph)
library(tidyverse)
library(ggraph)
V <- read.table(text = "x y
589.3438 6422.883
8762.6921 7789.147
7973.0883 4552.745
4100.8408 8108.702
6049.3329 6547.239",
header = T) %>%
rownames_to_column("name")
E <- matrix(c(0, 0, 0, 1, 0,
0, 0, 1, 0, 1,
0, 1, 0, 0, 1,
1, 0, 0, 0, 1,
0, 1, 1, 1, 0), nrow = 5, byrow = T) %>%
data.frame() %>%
rename_all(list(function(x) 1:5)) %>%
rownames_to_column(var = "from") %>%
gather(to, val, 2:6) %>%
filter(val == 1) %>%
select(from, to)
g <- graph_from_data_frame(E, vertices = V, directed = F)
现在来了ggraph
魔法。为了说明它的威力,我混合并匹配了各种边缘和节点geom
提供可能的样本ggraph
.
ggraph(g) +
geom_edge_link() +
geom_node_label(aes(label = name))
#> Using `nicely` as default layout
ggraph(g) +
geom_edge_arc() +
geom_node_point()
#> Using `nicely` as default layout
ggraph(g) +
geom_edge_diagonal() +
geom_node_text(aes(label = name), color = "blue")
#> Using `nicely` as default layout
原答案:
如果使用igraph
是一个选择,我会推荐它。在处理图表时这是一个非常有用的包。这是我使用 igraph 的方法:
library(igraph)
# convert V to a matrix and E to a graph
V <- data.matrix(V)
g <- graph_from_adjacency_matrix(E, mode="undirected")
plot.igraph(g, layout = V)
或者,如果您想要 ggplot 风格的方法,您可以使用ggnet2
来自GGally
包裹:
library(GGally)
V <- data.matrix(V)
# with ggnet2 you don't have to convert E to a graph
ggnet2(net = E, mode = V )