4

我正在尝试绘制网络图并仅显示 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
4

2 回答 2

10

这不是答案,而是对使用上述答案的任何未来访问者的评论。当我在不同的网络中尝试levels(name)时,它给出了错误的结果。tidygraph具有filter可在各种几何图形中用于过滤节点、边等的属性。

所以,geom_node_text如果写成上面的答案应该会更好:

geom_node_text(aes(filter=centrality > .6, label = name))
于 2018-05-16T08:28:46.280 回答
8

我以前从未使用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-approach 不起作用,因为它不会查看您的内部rt_tbl,而是尝试获取centrality不存在的 object 。但无论如何它都不起作用,因为您需要给它一个与数据长度相同的向量,但子集只返回与您的条件匹配的值。因此,使用ifelse更适合您的任务。

编辑:

顺便说一句,这是一个最小的可重现示例(至少我现在知道如何使用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)代替nameor levels(name)(就像我之前所做的那样),也许你也必须在我上面的解决方案中改变它......

但关于这一点,请查看下面的@Alper Yilmaz 解决方案。

于 2017-11-08T09:37:21.403 回答