如何修改ggplot+ggwordcloud词云图例中的文本内容
ggwordcloud词云图例文本显示NA的解决方法
问题背景
使用TidyTuesday数据集(统计《足球教练》中Roy Kent每集说fuck的次数)制作词云,首次使用ggwordcloud包时,发现词云图例中的文本显示为NA,需要修改为"FUCK"这类指定内容。
原始代码
环境配置
library(ggplot2) library(ggtext) library(ggwordcloud) library(showtext) library(tidyverse)
数据加载
tuesdata <- tidytuesdayR::tt_load(2023, week = 39) fuck <- tuesdata$richmondway
绘图数据处理
fuck_plot <- fuck |> select("Season_Episode", "F_count_RK", "Dating_flag", "Coaching_flag") |> mutate(word = "FUCK")
字体设置
font_add_google("Oswald", "os") showtext_auto() plot_font <- "os"
原始绘图代码
fp <- fuck_plot |> ggplot(aes(x = 0, y = 0, label = word, size = F_count_RK, color = Dating_flag)) + geom_text_wordcloud_area( aes(color = Dating_flag), eccentricity = .5, seed = 289, tstep = 0.04, family = "os", fontface = "bold", show.legend = TRUE ) + scale_size_area(max_size = 40) + scale_color_manual( labels = c("Hell No", "Hell Yea"), values = c("black", "#e0218a"), name = "Is Rick Dating Keeley?" ) + coord_cartesian( expand = FALSE ) + guides(size = "none") + theme_void() + theme( plot.margin = margin(0, 0, 0, 0), legend.position = c(0.5, 0.75) )
解决方案
问题根源是geom_text_wordcloud_area的图例默认使用label映射的内容,但所有数据的word值相同,导致图例文本被识别为NA。通过在guides中自定义颜色图例的符号文本即可解决:
修改后的绘图代码
fp <- fuck_plot |> ggplot(aes(x = 0, y = 0, label = word, size = F_count_RK, color = Dating_flag)) + geom_text_wordcloud_area( eccentricity = .5, seed = 289, tstep = 0.04, family = "os", fontface = "bold", show.legend = TRUE ) + scale_size_area(max_size = 40) + scale_color_manual( labels = c("Hell No", "Hell Yea"), values = c("black", "#e0218a"), name = "Is Rick Dating Keeley?" ) + coord_cartesian( expand = FALSE ) + guides( size = "none", # 强制替换图例中的文本为指定内容 color = guide_legend(override.aes = list(label = "FUCK")) ) + theme_void() + theme( plot.margin = margin(0, 0, 0, 0), legend.position = c(0.5, 0.75) )
关键修改说明
- 添加
color = guide_legend(override.aes = list(label = "FUCK"))到guides中,直接替换颜色图例的文本内容,将NA改为"FUCK"。 - 移除了
geom_text_wordcloud_area中重复的aes(color = Dating_flag),因为顶层ggplot(aes())已经包含该映射,重复定义无必要。
内容的提问来源于stack exchange,提问作者ZahlenZ
相关产品推荐
相关产品推荐

