ggwordcloud轻松绘制词云图

2023-11-13 10:42:42 浏览数 (2)

加载R包

代码语言:javascript复制
devtools::install_github("lepennec/ggwordcloud")
install.packages("ggwordcloud")
library(ggwordcloud)
library(tidyverse)
library(wordcloud2)

导入数据

代码语言:javascript复制
df <- demoFreq %>% head(200) %>% as_tibble()

绘制基础图

代码语言:javascript复制
ggplot(df,aes(label = word,size=freq))  
  geom_text_wordcloud()  
  theme_minimal()

修改形状

代码语言:javascript复制
ggplot(df,aes(label = word,size=freq))  
  geom_text_wordcloud(shape = "diamond")  
  theme_minimal()
代码语言:javascript复制
ggplot(df,aes(label = word,size=freq))  
  geom_text_wordcloud(shape = "star")  
  theme_minimal()

字体缩放

代码语言:javascript复制
ggplot(df,aes(label = word,size=freq))  
  geom_text_wordcloud(rm_outside = TRUE)   # 删除不合适的字体防止溢出
  scale_size_area(max_size = 10)  
  theme_minimal()

设置心形

代码语言:javascript复制
mask_png <- png::readPNG(system.file("extdata/hearth.png",
                                     package = "ggwordcloud", mustWork = TRUE))

ggplot(df, aes(label = word, size = freq))  
  geom_text_wordcloud(mask = mask_png,rm_outside = TRUE)  
  scale_size_area(max_size = 10)  
  theme_minimal()

设置单一颜色

代码语言:javascript复制
ggplot(df, aes(label = word, size = freq))  
  geom_text_wordcloud(mask = mask_png,rm_outside = TRUE,color="red")  
  scale_size_area(max_size = 10)  
  scale_color_discrete("red")  
  theme_minimal()

添加渐变色

代码语言:javascript复制
ggplot(df, aes(label = word,size = freq,color = freq))  
  geom_text_wordcloud(mask = mask_png,rm_outside = TRUE)  
  scale_size_area(max_size = 10)  
  theme_minimal()  
  scale_color_gradientn(colours = rev(RColorBrewer::brewer.pal(10, "RdBu"))) 

0 人点赞