代码之家  ›  专栏  ›  技术社区  ›  boshek

向tidygraph对象添加属性列

  •  0
  • boshek  · 技术社区  · 7 年前

    我试图弄清楚如何将属性数据添加到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 这个阴谋?

    于2019年3月11日由 reprex package

    1 回复  |  直到 7 年前
        1
  •  3
  •   Marius    7 年前

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

    Coloured labels

    推荐文章