我想通过ggplot或一些R内置函数在R中绘制标准G =(V,E)图。
我有一个包含顶点坐标的数据框:
> V
x y
1 589.3438 6422.883
2 8762.6921 7789.147
3 7973.0883 4552.745
4 4100.8408 8108.702
5 6049.3329 6547.239
和表示边缘的零一对称矩阵:
> E
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 1 0
[2,] 0 0 1 0 1
[3,] 0 1 0 0 1
[4,] 1 0 0 0 1
[5,] 0 1 1 1 0
我使用:
绘制顶点plotGraph <- function() {
qplot(x,
y,
data=V,
xlim=c(0,SIZE),
ylim=c(0,SIZE),
main="Graph"
)
}
如何在同一个图上绘制图形边缘?或者如何从(x1,y1)到(x2,y2)绘制单个边?
任何帮助都将不胜感激。
答案 0 :(得分:5)
编辑(2017年7月7日):
由于我最初回答了这个问题,我们已经发布了一个新的改进的网络/图表绘图包ggraph
,我认为它应该取代以下选项,所以我编辑了我的答案添加ggraph
选项:
首先,将顶点和边缘作为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 )