pus*_*t88 7 visualization r graph-visualization ggrepel ggraph
绘制网络时,如果节点的标签也可以避开网络边缘,那将是很好的选择。例如,在下面的示例中,可以将所有标签移到网络外部。我已经尝试了几个软件包,但是到目前为止,还没有找到一种可行的方法。有办法吗?下面的例子:
library(ggraph)
library(tidygraph)
reprex <- tibble(to = sample(1:10, 100,replace=T),
from = sample(1:10, 100,replace=T)
) %>%
as_tbl_graph()
V(reprex)$label1 <- rep("label",10)
reprex_plot <- reprex %>%
ggraph() +
geom_node_point() +
geom_edge_link(color="grey")+
geom_node_text(aes(label=label1),repel=T,force=100)+
theme_bw()
reprex_plot
Run Code Online (Sandbox Code Playgroud)
据我了解这里的问题,ggrepel
,它使用的包geom_node_text
,只能访问节点所在的层,而不能“看到”边缘。这使得它ggrepel
不太适合网络(或者我错过了一些东西)。
不幸的是,我也没有一个很好的解决方案来解决这个问题,尽管我已经寻找了一段时间了。以下是您(或任何人)如何转向更好的标签方式的两个建议ggraph()
:
所以我的一个想法是让网络布局算法为我们完成工作。我制作了另一组仅包含标签的节点。标签节点仅连接到它们标记的网络中的一个相应节点。开始了:
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")
Run Code Online (Sandbox Code Playgroud)
我在这里添加边缘颜色灰色,因为我们在最终图中将有两种不同的颜色。
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")
Run Code Online (Sandbox Code Playgroud)
现在我们有了带有标签节点的新图,我们可以进行绘图了。请注意,我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
Run Code Online (Sandbox Code Playgroud)
显然,还有很大的改进空间。标签现在距离节点非常远。它们仍然与自己的边缘重叠(尽管我认为这可以通过提供更好的 hjust 值来解决)。虽然这适用于自动布局,但其他布局可能会做奇怪的事情,具体取决于您的数据。我真的希望其他人能提出更好的解决方案。但我想我还是把它放在这里吧。也许有人感到受到启发。
解决该问题的另一种方法是在文本上使用白色背景。该解决方案的灵感来自于网络绘图 GUI 程序如何处理该问题。我们可以使用ggplot2
'sgeom_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()
Run Code Online (Sandbox Code Playgroud)
我删除了标签上的边框,并将它们直接放置在节点的上方 ( nudge_y = 0.1
)。您的结果可能会有所不同,具体取决于图的大小,因此您可能需要更改该值。
在较大的网络上,标签的白框可能会覆盖其他节点。