我想弄清楚如何在 ggraph
中使用经纬度布局但似乎无法通过语法工作。考虑使用从 iris
修改的一些数据的这个 reprex数据集:
data <- structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4, 4.6,
5, 4.4, 4.9, 5.4, 4.8), Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6,
3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4), Lon = c(-122.683, -122.688,
-122.686, -122.683, -122.678, -122.675, -122.674, -122.673, -122.676,
-122.674, -122.677, -122.68), Lat = c(45.523, 45.52, 45.514,
45.515, 45.513, 45.514, 45.517, 45.519, 45.519, 45.522, 45.524,
45.521)), class = "data.frame", .Names = c("Sepal.Length", "Sepal.Width",
"Lon", "Lat"), row.names = c(NA, -12L))
library(ggplot2)
library(igraph)
library(ggraph)
坐标位置的简单图如下所示:
ggplot(data, aes(x = Lon, y = Lat)) +
geom_point(size = 6)
layout
接受一个矩阵,所以我将在此处提取坐标并将其转换为矩阵:spatial_layout <- layout.norm(as.matrix(data[,c(3,4)]))
然后转
data
进入 igraph 对象:igraph_data <- graph_from_data_frame(data)
如果我用基本的
plot.igraph
绘图布局符合预期;每个点的空间坐标:plot.igraph(igraph_data, layout = spatial_layout)
现在这是我遇到问题的地方。我宁愿使用
ggraph
利用ggplot2
的力量.但是我不确定如何让它接受空间布局。这不起作用:ggraph(igraph_data, spatial_layout) +
geom_edge_link() +
geom_node_point(color = "black", size = 9, pch = 1) +
geom_node_text(aes(label = name))
Error in create_layout.igraph(graph, layout, ...) : Unknown layout
也不会尝试创建自定义布局:
create_layout(data, layout = "spatial_layout")
Error in create_layout.default(data, layout = "spatial_layout") :
No layout function defined for objects of class data.frame
手动将经纬度数据添加到 igraph 对象似乎也不起作用:
igraph_data$layout=cbind(E(igraph_data)$Lon,E(igraph_data)$Lat)
ggraph(igraph_data) +
geom_edge_link() +
geom_node_point(color = "black", size = 9, pch = 1) +
geom_node_text(aes(label = name))
Using
nicely
as default layout Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 12, 17
所以最终我的问题是如何将空间数据添加到
ggraph
布局?显然我在这里遗漏了一些东西,但我似乎无法找出正确的方法。
最佳答案
我们可以使用 ggraph::create_layout
进行等效的手动布局。 .但首先,我们需要使空间坐标的数量与我们传递的图中的顶点数量相匹配。看起来像 plot.igraph
正在默默地回收您的原始布局。
# must have columns named x and y
data2 <- data.frame(x = rep(spatial_layout[,1], length.out = 17),
y = rep(spatial_layout[,2], length.out = 17))
然后使用
?layout_igraph_manual
的帮助页面作为后续参数名称的指南。manual_layout <- create_layout(graph = igraph_data,
layout = "manual", node.positions = data2)
注意:我提出警告
Error: 'layout_igraph_manual' is not an exported object from 'namespace:ggraph'
当我直接调用函数时。然后我们就可以把它插到原来的了:
ggraph(manual_layout) +
geom_edge_link() +
geom_node_point(color = "black", size = 9, pch = 1) +
geom_node_text(aes(label = name))
默认情况下,轴限制不相同,但这是一个很小的
+ xlim(-2.5,2.5)#ish
调整。
关于r - 在 ggraph 中使用纬度/经度数据进行布局的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780464/