2

使用 R阅读Tidytext Mining -- 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”为红色,所有其他文本为黑色。

4

1 回答 1

2

没有可重复的示例,我通过链接并制作了一个小数据集来说明我的解决方案。

图书馆

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

于 2019-05-19T00:23:25.183 回答