向 tidygraph 对象添加属性列

Adding an attribute column to a tidygraph object

我正在尝试弄清楚如何将属性数据添加到专门用于绘图目的的 tidygraph 对象。我似乎无法弄清楚如何获取与变量级别关联的变量,并在我创建 tidygraph 对象以供稍后在绘图中使用时保留它。所以在下面的 reprex 中,我想按高度着色,但我不明白这种方法

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidygraph)
#> 
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#> 
#>     filter
library(ggraph)
#> Loading required package: ggplot2

starwars_graph <- starwars %>%
  filter(eye_color == "blue") %>% ## trim down the data
  select(species, homeworld,  height) %>%
  na.omit() %>% 
  as_tbl_graph()


ggraph(starwars_graph, layout = "nicely") +
  geom_edge_link() +
  geom_node_label(aes(label = name))


ggraph(starwars_graph, layout = "nicely") +
  geom_edge_link() +
  geom_node_label(aes(label = name, colour = height))
#> Error in FUN(X[[i]], ...): object 'height' not found

任何人都可以推荐任何将 height 添加到此情节的好方法吗?

reprex package (v0.2.1)

创建于 2019-03-11

目前,height是一条边属性(每个人的属性),为了创建一个节点属性,将应用于整个物种似乎你需要使用平均值将每个物种的多个成员分解为一个值:

sp_heights = starwars %>%
    group_by(species) %>%
    summarise(height = mean(height, na.rm = TRUE))

starwars_graph = starwars_graph %>%
    activate(nodes) %>%
    left_join(sp_heights, by = c("name" = "species"))

ggraph(starwars_graph, layout = "nicely") +
    geom_edge_link() +
    geom_node_label(aes(label = name, colour = height)) +
    scale_color_continuous(na.value = "black")

输出: