按组向ggplot添加颜色

Adding colour by group to ggplot

我已经分析了文本,并且正在尝试可视化三组单词的频率。我想为这三个组分别设置一种颜色,这样我所有的图表都可以很容易地进行比较。下面是我的数据结构和我用来制作图表的代码。我不确定如何为每个组分配自己的颜色并在我的脚本中重现它。目前它只是根据组产生不同深浅的蓝色。

谢谢

structure(list(group = c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 
2, 2, 2, 2, 3, 3, 3), word = c("happy", "dance", "pain", "pen", 
"feel", "head", "football", "year", "asthma", "contagious", "flowers", 
"lamp", "calendar", "phone", "cereal", "book", "acne", "low", 
"pain"), n = c(134, 138, 157, 195, 209, 213, 266, 414, 114, 114, 
126, 149, 182, 193, 205, 223, 103, 110, 118), row = c(1, 2, 3, 
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)), row.names = c(NA, 
-19L), class = c("tbl_df", "tbl", "data.frame"))

以及图表的代码

# Colours for the three groups
my_colors <- c("#FFDBCE", "#8CAEAE", "#beb6d7")


#Organise words by group 
wordsbygroup <- script %>% 
  group_by(group) %>%
  count(word, group, sort = TRUE) %>%
  slice(seq_len(8)) %>%
  ungroup() %>%
  arrange(group,n) %>%
  mutate(row = row_number()) 

#Visualise words by group 

wordsbygroup %>%
  ggplot(aes(row, n, fill = group)) +
  geom_col(show.legend = F) +
  labs(x = NULL, y = "Word Count") +
  ggtitle("Frequent Words by group") + 
  facet_wrap(~group, scales = "free_y","fixed_x") +
  scale_x_continuous(  # This handles replacement of row 
    breaks = wordsbygroup$row, # notice need to reuse data frame
    labels = wordsbygroup$word) +
  coord_flip()

我把你的填充组变成了一个因素,使组离散。

然后添加了 scale_fill_manual(values = my_colors) 来分配填充颜色。

wordsbygroup %>%
  ggplot(aes(row, n, fill = as.factor(group))) +
  geom_col(show.legend = F) +
  labs(x = NULL, y = "Word Count") +
  ggtitle("Frequent Words by group") + 
  facet_wrap(~group, scales = "free_y","fixed_x") +
  scale_x_continuous(  # This handles replacement of row 
    breaks = wordsbygroup$row, # notice need to reuse data frame
    labels = wordsbygroup$word) +
  scale_fill_manual(values = my_colors) + 
  coord_flip()