ggraph 根据关键字更改 geom_node_text 颜色

ggraph change geom_node_text color based off key words

正在阅读 Tidytext Mining with R --https://www.tidytextmining.com/nasa.html -- 我有以下问题:

默认情况下,节点文本颜色为黑色,我可以全局调整颜色 但是否可以使用默认颜色黑色,而使用其他基于关键字的颜色?

library(ggplot2)
library(igraph)
library(ggraph)

set.seed(1234)
title_word_pairs %>%
 filter(n >= 250) %>%
 graph_from_data_frame() %>%
 ggraph(layout = "fr") +
 geom_edge_link(aes(edge_alpha = n, edge_width = n)
 , edge_colour = "cyan4") +
 geom_node_point(size = 5) +
 geom_node_text(aes(label = name), repel = TRUE
 , point.padding = unit(0.2, "lines"), colour="red") +
 theme_void()

在上图中,"land" 和 "data" 为红色,所有其他文本为黑色。

由于没有可重现的示例,我浏览了 link 并制作了一个小数据集来说明我的解决方案。

图书馆

library(dplyr)
library(widyr)
library(ggplot2)
library(igraph)
library(ggraph)

数据

title_word_pairs1 <- structure(list(item1 = c("phase", "ges", "phase", "1", "phase", 
                                              "phase", "ges", "disc", "phase", "phase"), 
                                    item2 = c("ii", "disc", "system", "version", "space",
                                              "based", "degree", "degree", "low", "power"), 
                                    n = c(2498, 1201, 948, 678, 637, 601, 
                                          582, 582, 480, 441)), 
                                row.names = c(NA, -10L), 
                                class = c("tbl_df", "tbl", data.frame"))

使用 ggplot 数据创建颜色列表:

在这里,我创建了没有节点、文本等的 igraph,然后使用它的数据制作了一个所需颜色的列表。

set.seed(1)
g <- title_word_pairs1 %>%
  filter(nnn >= 250) %>%
  graph_from_data_frame() %>%
  ggraph(layout = "fr")

mcolor <- g$data %>% mutate(mcolor = if_else(name %in% c("low", "space"), 
                                     "blue", "black")) %>% select(mcolor)

g +
  geom_edge_link(aes(edge_alpha = n, edge_width = n)
                 , edge_colour = "cyan4") +
  geom_node_point(size = 5) +
  geom_node_text(aes(label = name), repel = TRUE
                 , point.padding = unit(0.2, "lines"), colour=mcolor$mcolor) +
  theme_void() + theme(legend.position="none")

reprex package (v0.2.1)

于 2019-05-19 创建

正在将 ggplot_build 对象颜色操作为所需的颜色:

我基本上做的是绘制情节,然后操纵 ggplot 对象以获得所需的颜色。

set.seed(1)
g <- title_word_pairs1 %>%
  filter(n >= 250) %>%
  graph_from_data_frame() %>%
  ggraph(layout = "fr") +
  geom_edge_link(aes(edge_alpha = n, edge_width = n)
                 , edge_colour = "cyan4") +
  geom_node_point(size = 5) +
  geom_node_text(aes(label = name), repel = TRUE
                 , point.padding = unit(0.2, "lines"), colour="red") +
  theme_void() + theme(legend.position="none")

g

gg <- ggplot_build(g)

gg$data[[3]] <- gg$data[[3]] %>%
                             mutate(colour = if_else(label %in% c("low", "space"), 
                                                    "blue", "black"))

gt <- ggplot_gtable(gg)

plot(gt)

reprex package (v0.2.1)

于 2019-05-18 创建