R:如何在ggraph中控制边缘的行为

时间:2018-08-29 15:34:40

标签: r ggplot2 ggraph

我正面临这个问题:我得到了一些像这样的数据:

library(tidyverse)
library(tidygraph)
library(ggraph)
library(ggrepel)

edges <- data.frame(a=c('k','k','k','k','k','z','z'),
                    b=c('b','b','b','b','c','b','c'), costant = 1)
  a b costant
1 k b       1
2 k b       1
3 k b       1
4 k b       1
5 k c       1
6 z b       1
7 z c       1

现在,我希望有一个带有ggraph的图,该图具有带有权重的节点和边。所以我这样工作:

# first I calculated the edges weights
edges1 <- edges%>% group_by(a,b) %>% summarise(weight = sum(costant))
> edges1
# A tibble: 4 x 3
# Groups:   a [?]
  a     b     weight
  <fct> <fct>  <dbl>
1 k     b          4
2 k     c          1
3 z     b          1
4 z     c          1

然后是节点:

nodes <- rbind(data.frame(word = edges$a, n = 1),data.frame(word = edges$b, n = 1)) %>%
 group_by(word) %>%
summarise(n = sum(n))
> nodes
# A tibble: 4 x 2
  word      n
  <fct> <dbl>
1 k         5
2 z         2
3 b         5
4 c         2

到目前为止,一切正常。现在,以this为例:

tidy <- tbl_graph(nodes = nodes, edges = edges1, directed = T)
tidy <- tidy %>% 
  activate(edges) %>% 
  arrange(desc(weight)
)

突然我画了图:

ggraph(tidy, layout = "gem") + 
  geom_node_point(aes(size=n)) +
  geom_edge_link(aes(width = weight), alpha = 0.8) + 
  scale_edge_width(range = c(0.2, 2)) +
  geom_text_repel(aes(x = x, y=y , label=word)) 

但是结果是这样的:

enter image description here

我不知道为什么在k和z之间有一条线,因为那条边不存在。

预先感谢。

1 个答案:

答案 0 :(得分:1)

这似乎是由于tbl_graph通过edge1factor的tibble节点从integer转换为as.integer而不考虑nodes微动,这是错误的根源。如果我们将边缘节点正确地预先转换为整数,它将按预期工作。

edges <- data.frame(a=c('k','k','k','k','k','z','z'),
                    b=c('b','b','b','b','c','b','c'), costant = 1)
edges1 <- edges%>% group_by(a,b) %>% summarise(weight = sum(costant))

nodes <- rbind(data.frame(word = edges$a, n = 1),data.frame(word = edges$b, n = 1)) %>%
  group_by(word) %>%
  summarise(n = sum(n))

edges2 <- edges1 # save edges with factor node labels into edge2
# convert 'from' and 'to' factor columns to integer columns correctly 
# with the nodes tibble's corresponding matched index values 
edges1$a <- match(edges1$a, nodes$word) 
edges1$b <- match(edges1$b, nodes$word)

tidy <- tbl_graph(nodes = nodes, edges = edges1, directed = T)
tidy <- tidy %>% 
  activate(edges) %>% 
  arrange(desc(weight)
  ) 

ggraph(tidy, layout = "gem") + 
   geom_node_point(aes(size=n)) +
   geom_edge_link(aes(width = weight), arrow = arrow(length = unit(4, 'mm')), end_cap = circle(3, 'mm'), alpha = 0.8) + 
   scale_edge_width(range = c(0.2, 2)) +
   geom_text_repel(aes(x = x, y=y , label=word)) 

edges2 # compare the edges in the following tibble with the next figure
# A tibble: 4 x 3
# Groups:   a [?]
    a     b     weight
  <fct> <fct>  <dbl>
#1 k     b       4
#2 k     c       1
#3 z     b       1
#4 z     c       1

enter image description here