ggplot绘图图例出现NA(源于‘Warning: NAs introduced by coercion’警告)求助
问题分析与解决办法
问题根源
你遇到的NAs introduced by coercion警告和图例出现NA的问题,本质是字符型变量source中存在无法转换为数值的内容,且你绕了没必要的弯路:字符型变量直接转因子就能给ggplot做颜色映射,根本不需要先转数值再用cut。
解决方案
方案1:直接将字符型source转为因子(推荐)
这是最简洁且避免NA问题的方法,ggplot原生支持因子变量的离散颜色映射:
a2 <- read.csv(file = "dataset.csv") library("dplyr") library("ggpubr") library("ggplot2") # 直接把source转成带自定义标签的因子 a2 <- a2 %>% mutate(source_group = factor(source, levels = c("1", "2"), # 对应原始的"1""2"取值 labels = c("Young", "Adult"))) # 设置显示的类别名称 # 绘制图形(调用新生成的source_group做颜色映射) ggplot(data = a2, aes(x = familiar_place, y = commit3, color=source_group))+ geom_point()+ geom_jitter(size = 1.3)+ # 无需重复声明color映射,继承上层即可 ggpubr::color_palette("jco")+ ggpubr::theme_classic2()+ theme(legend.position ="top", legend.direction = "horizontal", plot.margin = margin(0.5, 0.5, 0.5, 0.5, "cm"), plot.title = element_text(hjust = 0.5))+ labs(color = "Age of Voice Messaging", x = "Familiarity with Location", y = "Commitment to Water Conservation", title = "Water Conservation Commitment by Location Familiarity and \n Age of Voice Messaging")
方案2:修复原方法的NA问题(若坚持用数值转cut逻辑)
如果你一定要保留转数值再cut的流程,先排查并清理source中的异常值:
# 先查看source列的所有唯一值,确认是否存在非"1""2"的内容 unique(a2$source) # 若存在空格、特殊字符等,先清理数据 a2$source <- trimws(a2$source) # 转数值后用cut划分,同时确保边界值被正确包含 a2$source_numeric <- as.numeric(a2$source) a2$source_numeric <- cut(a2$source_numeric, breaks=c(0, 1.1, 2.1), labels=c('Young', 'Adult'), include.lowest = TRUE) # 保证1和2被归类到对应组
清理后绘图,NA值就不会出现在图例中了。
补充说明
你之前直接用字符型source做颜色映射无效,大概率是因为source未被识别为离散变量(或数据中存在异常值干扰),转成因子后就能正常触发ggplot的离散颜色映射逻辑。
内容的提问来源于stack exchange,提问作者Richard Xi
相关产品推荐
相关产品推荐

