ggraph 在 geom_node_point 中使用填充和颜色

ggraph use fill and color in geom_node_point

我正在尝试制作一个样本自我网络图,但使用“填充”为节点着色对我不起作用。这可能是一个微不足道的问题,但我无法弄清楚问题所在。这是我的代码:

library(tidyverse)
library(igraph)
library(ggraph)
library(tidygraph)
library(ggplot2)

edges <- read.table(text = 
"ego    wave    fid1        fid2        fid3        fid4        fid5
 Ego    1       Friend_A    Friend_B    Friend_C    NA        Friend_D
 Ego    2       Friend_E    Friend_F    NA        NA          Friend_G
 Ego    3       Friend_H    NA        Friend_I  Friend_G    Friend_J
 Ego    4       Friend_H    NA        NA        NA        NA
 Ego    5       Friend_K    NA        NA          NA          Friend_F", header = TRUE) %>%

  mutate_all(function(x) gsub("_"," ",x)) %>%
  pivot_longer(.,
               cols = c(fid1:fid5)) %>%
  select(., ego, alter = value, wave) %>% na.omit()

ego <-   as.data.frame(edges$ego) %>%
         rename("id" = "edges$ego")
alter <- as.data.frame(edges$alter) %>%
         rename("id" = "edges$alter")

nodes <- bind_rows(ego, alter) %>% distinct() %>%
         mutate(label = case_when(id == "Ego" ~ 1,
                                  TRUE ~ 0))


g1 <- graph_from_data_frame(d = filter(edges, wave == 1), vertices = nodes, directed = TRUE) %>%
      delete.vertices(., which(degree(.)==0))


as_tbl_graph(g1) %>%
      create_layout(., layout = 'stress') %>%
      ggraph(.) + 
      geom_edge_link(color = "grey", 
                     arrow = arrow(type = "closed",
                                   angle = 25,
                                   length = unit(1.5, 'mm')), 
                     end_cap = circle(3.5, 'mm'), 
                     width = 0.5, show.legend = FALSE) +        
      geom_node_point(aes(fill = factor(label)), size = 7, color = "black") +
      scale_fill_hue(l=40) +
      geom_node_text(aes(label = name), vjust = -1) +
      theme_graph()+
      theme(legend.position = "none")+
      labs(title = "Wave 1")

用这段代码我得到了这个情节:

但是,我的目标是让节点由标签变量着色(其中 ego 的颜色不同于 alters),并在每个节点周围有一个黑色轮廓。知道我在这里做错了什么吗?

更新

通过 tjebo 的输入(非常感谢!)(“...并且在每个节点周围都有一个黑色轮廓”)的解决方案可以是:

  • 更改此行

geom_node_point(aes(fill = factor(label)), size = 7, color = "black") +

geom_node_point(aes(fill = factor(label)), shape = 21, size = 7, color = "black") +

输出

先试试

更改:geom_node_point(aes(fill = factor(label)), size = 7, color = "black") +geom_node_point(aes(color = factor(label)), size = 7) +

这是对我上面的评论的扩展,也是一个答案。例子直接取自?geom_node_point.

你基本上问了一个“如何改变点的填充和颜色”的问题,已经回答了很多次了。方法当然不止一种,下面我只是用了一种不同的形状。

library(ggraph)
#> Loading required package: ggplot2
library(tidygraph)

gr <- create_notable('bull') %>%
  mutate(class = sample(letters[1:3], n(), replace = TRUE))

ggraph(gr, 'stress') + 
  geom_node_point(aes(fill = class), shape = 21, size = 7, color = "black")

reprex package (v1.0.0)

于 2021-04-05 创建