ggplot 3.5.1中scale_color_manual缺失类别图例无颜色问题求助
解决ggplot2 3.5.1中无数据分箱图例无颜色的问题
在ggplot2 3.5.1中,直接在aes()内用lvls_expand()扩展因子水平无法确保未出现的分箱加载对应颜色,以下两种方法可解决该问题:
方法1:提前转换为包含所有水平的因子
先将分类变量转换为包含所有目标分箱的因子,再结合drop=FALSE参数强制显示全部分箱:
library(ggplot2) Data <- data.frame(x = c(1,2,3,4), y = c(4:1), class = c('a','b','a','b')) # 预定义所有分箱水平 Data$class <- factor(Data$class, levels = c('a', 'b', 'c')) ggplot(Data, aes(x = x, y = y, color = class)) + geom_point() + scale_color_manual( values = c(a = 'red', b = 'blue', c = 'green'), name = "Legend", drop = FALSE )
方法2:在颜色刻度中指定limits参数
无需提前修改数据,直接在scale_color_manual()中用limits参数指定所有分箱水平,配合drop=FALSE即可:
library(ggplot2) Data <- data.frame(x = c(1,2,3,4), y = c(4:1), class = c('a','b','a','b')) ggplot(Data, aes(x = x, y = y, color = class)) + geom_point() + scale_color_manual( values = c(a = 'red', b = 'blue', c = 'green'), name = "Legend", limits = c('a', 'b', 'c'), drop = FALSE )
原理说明
ggplot2 3.5.1对未在数据中出现的因子水平的图例渲染逻辑做了调整,通过预定义因子水平或在刻度中指定limits,能明确告诉ggplot2需要保留所有分箱,再加上drop=FALSE阻止自动丢弃无数据的水平,即可让图例完整显示所有分箱及对应颜色。
内容的提问来源于stack exchange,提问作者Brendanb
相关产品推荐
相关产品推荐

