我正在尝试绘制网络图并仅显示geom_node_text的标签,这些标签的中心分数高于特定阈值。我的代码如下:
rt_tbl %>%
mutate(centrality = centrality_authority()) %>%
ggraph(layout = 'kk') +
geom_edge_link(aes(), colour = "gray", alpha = 0.5) +
geom_node_point(aes(size = centrality, colour = centrality)) +
geom_node_text(data=subset(centrality > 0.6), aes(centrality, label=name)) +
theme_graph(base_family = "Roboto Condensed", base_size = 13)
我遇到以下错误:
Error in subset(centrality > 100) : object 'centrality' not found
我的数据如下:
# A tbl_graph: 1589 nodes and 3992 edges
# A directed multigraph with 3 components
# Node Data: 1,589 x 3 (active)
name degree centrality
<chr> <dbl> <dbl>
1 Ashinlay1970 35 0.90053429
2 WinTunMin1 25 0.66408597
3 Yaminayeyaohn1 2 0.06080755
4 TUNOO00655880 3 0.07609831
5 inewagency 8 0.21569006
6 KSwe03 4 0.12416238
# ... with 1,583 more rows
# Edge Data: 3,992 x 2
from to
<int> <int>
1 1 48
2 1 49
3 1 1
# ... with 3,989 more rows
答案 0 :(得分:3)
我以前从未使用过ggraph
,你应该提供一个可重复的最小例子,但试试这个:
rt_tbl %>%
mutate(centrality = centrality_authority()) %>%
ggraph(layout = 'kk') +
geom_edge_link(aes(), colour = "gray", alpha = 0.5) +
geom_node_point(aes(size = centrality, colour = centrality)) +
geom_node_text(aes(label=ifelse(centrality > .6, name, NA))) +
theme_graph(base_family = "Roboto Condensed", base_size = 13)
您的subset
- 方法不起作用,因为它不会查看rt_tbl
内部,但会尝试获取不存在的对象centrality
。但它无论如何都不会起作用,因为你需要给它一个与数据长度相同的向量,但子集只返回符合你条件的值。因此,使用ifelse
更适合您的任务。
BTW 这个是一个可重复性最小的例子(至少我现在知道如何使用ggraph
):
library(tidygraph)
library(ggraph)
rt_tble <- tidygraph::create_star(10) %>%
mutate(centrality = centrality_authority(),
name = LETTERS[1:10])
ggraph(graph = rt_tble) +
geom_edge_link() +
geom_node_point(aes(size = centrality, colour = centrality)) +
geom_node_text(aes(label = ifelse(centrality > .6, as.character(name), NA_character_)))
我必须使用as.character(name)
代替name
或levels(name)
(就像我之前所做的那样),也许你必须在上面的解决方案中改变它......
但关于这一点,请看下面的@Alper Yilmaz解决方案。
答案 1 :(得分:3)
这不是一个答案,而是对使用上述答案的任何未来访客的评论。
当我在不同的网络中尝试levels(name)
时,它给出了错误的结果。 tidygraph
具有filter
属性,可用于各种geoms以过滤节点,边缘等。
因此,如果写成:
,上面答案的geom_node_text
行应该会更好
geom_node_text(aes(filter=centrality > .6, label = name))