如何移除ggplot2中geom_histogram柱状图的多余轮廓线
解决ggplot2直方图零值柱子轮廓线问题
我用color参数给直方图的柱子添加红色轮廓,但数据存在间隙时,零值对应的柱子也会显示红色轮廓线,导致出现贯穿整张图的线条,视觉效果很差。以下是基于mtcars数据集的最小可复现代码:
library(ggplot2) data(mtcars) ggplot(mtcars, aes(x=mpg)) + geom_histogram(bins=15, colour='red')
之前我尝试用添加白色水平线的方法隐藏这条线,但想找一种不需要额外geom的更优方案:
library(ggplot2) data(mtcars) ggplot(mtcars, aes(x=mpg)) + geom_histogram(bins=15, colour='red') + geom_hline(yintercept = 0, color = "white")
更优解决方案
方法一:提前统计并过滤数据
先统计直方图的分组数据,过滤掉计数为0的组,再用geom_col绘制:
library(ggplot2) data(mtcars) # 统计直方图的bin数据 hist_data <- ggplot_build(ggplot(mtcars, aes(x=mpg)) + geom_histogram(bins=15))$data[[1]] # 过滤零计数组 hist_data_filtered <- subset(hist_data, count > 0) # 绘制直方图 ggplot(hist_data_filtered, aes(x=x, y=count)) + geom_col(fill="grey", colour="red") + xlab("mpg")
方法二:用after_stat()动态设置轮廓色
直接在geom_histogram中利用after_stat()访问计算后的计数,当count为0时将轮廓色设为透明(NA):
library(ggplot2) data(mtcars) ggplot(mtcars, aes(x=mpg)) + geom_histogram( bins=15, colour=after_stat(ifelse(count == 0, NA, "red")), fill="grey" )
第二种方法更简洁,无需提前处理数据,直接通过动态映射实现只给有数据的柱子添加红色轮廓线,零值柱子的轮廓会自动隐藏。
内容的提问来源于stack exchange,提问作者Seth Goodnight
相关产品推荐
相关产品推荐

