微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

按组添加颜色到ggplot

如何解决按组添加颜色到ggplot

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

谢谢

structure(list(group = c(1,1,2,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,126,149,182,193,205,223,103,110,118),row = c(1,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()

graph output

解决方法

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

然后添加 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()

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。