2

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

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 包(v0.2.1)于 2019 年 3 月 11 日创建

4

1 回答 1

3

目前,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")

输出:

彩色标签

于 2019-03-11T23:28:56.807 回答