如何在ggplot2的geom_count绘图中隐藏0值计数标记?
解决ggplot2中geom_count() count=0时仍显示蓝色标记的问题
问题核心:使用geom_count()映射count=0时,即使设置scale_size的range包含0,仍会出现微小蓝色标记,以下是几种直接有效的解决方式:
方法1:过滤count=0的数据再绘制蓝色标记
直接在第二个geom_count中指定仅使用count>0的数据集,彻底跳过count为0的行,不绘制对应标记:
ggplot(df, aes(x = week, y = dataset)) + geom_count(aes(size=total), colour="lightgrey") + # 仅保留count>0的数据绘制蓝色点 geom_count(data = df[df$count > 0, ], aes(size=count), colour="cornflowerblue") + scale_size(range = c(0,15), breaks=c(0,10,20,30,40,50)) + theme_minimal() + labs(y = "", x = "") + scale_y_discrete(limits=rev)
方法2:将count=0的size映射为NA
利用ggplot会忽略NA值的特性,把count=0对应的size设为NA,让这类点自动不显示:
ggplot(df, aes(x = week, y = dataset)) + geom_count(aes(size=total), colour="lightgrey") + # 把count=0的size替换为NA geom_count(aes(size=ifelse(count == 0, NA, count)), colour="cornflowerblue") + scale_size(range = c(0,15), breaks=c(0,10,20,30,40,50)) + theme_minimal() + labs(y = "", x = "") + scale_y_discrete(limits=rev)
方法3:限制scale_size的取值范围
通过scale_size的limits参数排除0值,让count=0的点因超出范围被剔除,但这种方式会改变size的缩放基准,需根据需求调整:
ggplot(df, aes(x = week, y = dataset)) + geom_count(aes(size=total), colour="lightgrey") + geom_count(aes(size=count), colour="cornflowerblue") + # 限制size最小值为1,自动过滤0值 scale_size(range = c(0,15), breaks=c(0,10,20,30,40,50), limits = c(1, 50)) + theme_minimal() + labs(y = "", x = "") + scale_y_discrete(limits=rev)
内容的提问来源于stack exchange,提问作者mri
相关产品推荐
相关产品推荐

