gpt4 book ai didi

r - 在 R 中绘制图形 G=(V,E)

转载 作者:行者123 更新时间:2023-12-01 11:22:49 25 4
gpt4 key购买 nike

我想通过 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) 的单边?

如有任何帮助,我们将不胜感激。

最佳答案

编辑(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)

igraph output

或者,如果你想要一个 ggplot 风格的方法,你可以使用 GGally 包中的 ggnet2:

library(GGally)

V <- data.matrix(V)
# with ggnet2 you don't have to convert E to a graph

ggnet2(net = E, mode = V )

ggnet2 output

关于r - 在 R 中绘制图形 G=(V,E),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40332501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com