微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 igraph 在 R 中绘制带有坐标的节点

如何解决使用 igraph 在 R 中绘制带有坐标的节点

我有一个ma​​in一个元数据数据框 Meta

这是图表。

city <- data.frame(from = c("London","Paris","Beijing","Berlin"),to = c("Beijing","Berlin","London","Paris"))
main <- graph_from_data_frame(city)

这是数据框。

Meta <- data.frame(name = c("Paris","Hong Kong","Rome","Madrid"),latitude = c(48.52,22.26,51.30,41.54,52.30,39.9,40.23),longitude = c(2.17,114.12,0.10,12.29,13.25,116.3,3.43))

由于图在Meta中只有一部分城市,我决定将纬度和经度从Meta分配给main 作为顶点属性

V(main)$latitude <- Meta$latitude[match(V(main)$from,Meta$name)]
V(main)$longitude <- Meta$longitude[match(V(main)$from,Meta$name)]

之后,我尝试用它们的纬度和经度来布局节点。

location <- matrix(c(V(main)$latitude,V(main)$longitude),ncol = 2)
plot(main,vertex.label = NA,vertex.size = 5,edge.width = 0.5,layout = location)

问题是我发现这些节点的位置不对。我不知道我哪里出错了。

解决方法

这是 igraph 绘图的一个特点。如果您查看页面 help(igraph.plotting),您会发现:

rescale
Logical constant,whether to rescale the coordinates to the [-1,1]x[-1,1](x[-1,1])
  interval. This parameter is not implemented for tkplot. 
Defaults to TRUE,the layout will be rescaled.

因此,即使您的布局(位置)的范围为 [39.9,52.3]x[0.1-116.3],plot 的默认形式也会将绘图更改为区域 [-1,1]x[[ -1,1]。您可以使用 rescale 参数来抑制这种行为,但不是 igraph 仍将默认使用绘图区域 [-1,1]x[[-1,1] 并且您的图形将简单地超出绘图区。因此,您还必须指定适当的 xlimylim。但同样,默认情况下,igraph 将强制该区域的纵横比为 1。由于数据中的经纬度有些不平衡,您可能还想调整 asp 参数。把这一切放在一起,我明白了

plot(main,vertex.label = NA,vertex.size = 5,edge.width = 0.5,layout = location,rescale=FALSE,asp=0,xlim = range(V(main)$latitude),ylim = range(V(main)$longitude))

现在顶点坐标将与数据中的经纬度匹配。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。