据我了解这里的问题,ggrepel
,这是使用的包geom_node_text
,只能访问节点所在的层,而不能“看到”边缘。这使得ggrepel
不太适合网络(或者我错过了一些东西)。
不幸的是,我也没有一个很好的解决方案来解决这个问题,尽管我已经寻找了一段时间了。这里有两个建议,您(或任何人)可以如何转向更好的标签方式ggraph()
:
1:文本作为节点
所以我的一个想法是让网络布局算法为我们完成工作。我制作了另一组仅包含标签的节点。标签节点仅连接到它们标记的网络中的一个相应节点。开始了:
library(dplyr)
library(ggraph)
library(tidygraph)
set.seed(123)
reprex <- tibble(from = sample(1:10, 100, replace = TRUE),
to = sample(1:10, 100, replace = TRUE)) %>%
as_tbl_graph() %>%
activate(edges) %>%
mutate(color = "grey")
我在这里添加边缘颜色灰色,因为我们在最终图中将有两种不同的颜色。
nodes <- reprex %>%
activate(nodes) %>%
as_tibble() # extract data.frame of nodes
# create new graph with just the lables
labels <- tibble(from = 1:10,
to = 11:20) %>%
as_tbl_graph() %>%
activate(nodes) %>%
mutate(label1 = "label",
is_label = !name %in% nodes$name) %>%
activate(edges) %>%
mutate(color = "black")
# join graph and labels
new_graph <- graph_join(labels, reprex, by = "name")
现在我们有了带有标签节点的新图,我们可以进行绘图了。请注意,我添加了一个变量is_label
到新图,以便我们可以使用不同的节点形状并确保仅标记标签节点:
reprex_plot <- new_graph %>%
ggraph() +
geom_edge_link(aes(color = color)) +
geom_node_point(aes(filter = !is_label, shape = "circle"), show.legend = FALSE) +
scale_edge_color_identity() +
geom_node_text(aes(filter = is_label, label = label1), hjust = -0.1) +
theme_void()
reprex_plot
显然,还有很大的改进空间。标签现在距离节点非常远。它们仍然与自己的边缘重叠(尽管我认为这可以通过提供更好的 hjust 值来解决)。虽然这适用于自动布局,但其他布局可能会做奇怪的事情,具体取决于您的数据。我真的希望其他人能提出更好的解决方案。但我想我还是把它放在这里吧。也许有人感到受到启发。
2:用标签代替文字
解决该问题的另一种方法是在文本上使用白色背景。该解决方案的灵感来自于网络绘图 GUI 程序如何处理该问题。我们可以用ggplot2
's geom_label
为此,虽然geom_node_label()
也会达到同样的效果。这个解决方案更加简单,但也有局限性。这是一个管道中的全部内容:
tibble(from = sample(1:10, 100, replace = TRUE),
to = sample(1:10, 100, replace = TRUE)) %>%
as_tbl_graph() %>%
activate(nodes) %>%
mutate(label1 = "label") %>%
ggraph() +
geom_edge_link(color = "grey") +
geom_node_point() +
geom_label(aes(x = x, y = y, label = label1), nudge_y = 0.1, label.size = NA) +
theme_void()
我删除了标签上的边框并将它们直接放置在节点上方(nudge_y = 0.1
)。您的结果可能会有所不同,具体取决于图的大小,因此您可能需要更改该值。
在较大的网络上,标签的白框可能会覆盖其他节点。