【问题标题】:Placing geom labels outside of circular layout in ggraph/ggplot2在 ggraph/ggplot2 中将几何标签放置在圆形布局之外
【发布时间】:2020-10-15 08:13:15
【问题描述】:

我正在尝试使用圆形布局中的标记节点生成交互网络图。我拼凑了一个功能脚本,显示了我想要与 ggraph 的连接,但我不知道如何相对于圆形排列中的位置定位节点标签,因此它们不会与连接线重叠地点。有人在使用 igraph (Placing vertex.label outside a circular layout in igraph) 时针对同样的问题发布了一个非常好的解决方案;但我认为这不适用于 ggraph,因为计算节点位置的方式似乎不同。我更喜欢为此使用 ggraph,因为它具有内置的图例功能,可以让我的生活更轻松。这是我目前所拥有的:

library(igraph)
library(tidyverse)
library(ggraph)

# Create example matrix
id <- c("s01", "s02", "s03", "s04", "s05")
s01 <- c(0, 0, 0, 1, 1)
s02 <- c(0, 0, 1, 1, 1)
s03 <- c(1, 0, 0, 0, 1)
s04 <- c(0, 1, 0, 0, 0)
s05 <- c(0, 0, 0, 0, 0)
links <- data.frame(id, s01, s02, s03, s04, s05)
links <- column_to_rownames(links, var = "id")
links <- as.matrix(links)
expertise <- c("neuro", "micro", "phys", "phys", "neuro")
nodes <- data.frame(id, expertise)

# Generate igraph object
network <- graph_from_adjacency_matrix(links, weighted = NULL, mode = "undirected")

# Generate plot
ggraph(network, layout = "circle") + geom_edge_arc(color = "darkgray", strength = 0.15) + 
geom_node_point(size = 8, aes(color = nodes$expertise)) + geom_node_text(aes(label = id), nudge_y = -0.2) + 
theme_void()

这会生成以下图:

问题在于像 s02 这样的标签在网络内部,这成为更密集的图的问题。

有没有办法将所有标签放在节点圈之外?任何帮助将不胜感激!

【问题讨论】:

标签: r ggplot2 ggraph


【解决方案1】:

这并不完全令人满意,因为它需要将绘图分配为中间步骤,因为 geom nudge 参数不使用函数,但您可以相对于节点 xy 坐标向外轻推标签:

library(igraph)
library(ggplot2)
library(ggraph)

# Generate igraph object
network <- graph_from_adjacency_matrix(links, weighted = NULL, mode = "undirected")

# Generate plot
p <- ggraph(network, layout = "circle") +
  geom_edge_arc(color = "darkgray", strength = 0.15) + 
  geom_node_point(size = 8, aes(color = nodes$expertise)) +
  theme_void()

p + 
  geom_node_text(aes(label = id), nudge_x = p$data$x * .1, nudge_y = p$data$y * .1)

【讨论】:

  • 太棒了!我只是在一个更复杂的数据集上尝试了这个,效果很好。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多