使用ggplot绘制负值区分配色、共享统一y轴刻度的双直方图
统一y轴刻度、正负值分色的ggplot2直方图实现
核心调整点
- 强制对齐y轴范围:提前测算两组数据的最大分箱计数值,为两张直方图设置完全一致的y轴上下限与留白规则,避免自动缩放导致的刻度不匹配
- 正负值自动分色:依托分箱统计后的中间值自动判定数据正负,为正值、负值匹配独立配色,无需手动拆分数据集
可复用实现代码
library(tidyverse) library(gridExtra) # 数据准备:加载包含DiffMedianHourlyPercent、DiffMeanHourlyPercent字段的本地数据集 # 统一绘图参数 bin_width <- 2 x_filter_range <- c(-100, 100) # 预先计算双图共同y轴范围 max_count_med <- dat %>% filter(between(DiffMedianHourlyPercent, x_filter_range[1], x_filter_range[2])) %>% pull(DiffMedianHourlyPercent) %>% {ggplot() + geom_histogram(aes(x = .), binwidth = bin_width)} %>% layer_data() %>% pull(count) %>% max() max_count_mean <- dat %>% filter(between(DiffMeanHourlyPercent, x_filter_range[1], x_filter_range[2])) %>% pull(DiffMeanHourlyPercent) %>% {ggplot() + geom_histogram(aes(x = .), binwidth = bin_width)} %>% layer_data() %>% pull(count) %>% max() shared_ylim <- c(0, ceiling(max(max_count_med, max_count_mean) / 100) * 100) # 绘制中位数时薪差直方图 p1 <- dat %>% filter(between(DiffMedianHourlyPercent, x_filter_range[1], x_filter_range[2])) %>% ggplot(aes(x = DiffMedianHourlyPercent)) + geom_histogram( aes(fill = after_stat(x > 0)), binwidth = bin_width, color = "white", linewidth = 0.3 ) + scale_fill_manual( values = c("TRUE" = "#e6550d", "FALSE" = "#3182bd"), labels = c("TRUE" = "女性薪酬占优", "FALSE" = "男性薪酬占优") ) + scale_y_continuous(limits = shared_ylim, expand = expansion(mult = c(0, 0.05))) + labs(x = "中位数时薪差(%)", y = "对应企业数量", fill = "差异方向") + theme_bw() + theme(legend.position = "bottom") # 绘制平均时薪差直方图 p2 <- dat %>% filter(between(DiffMeanHourlyPercent, x_filter_range[1], x_filter_range[2])) %>% ggplot(aes(x = DiffMeanHourlyPercent)) + geom_histogram( aes(fill = after_stat(x > 0)), binwidth = bin_width, color = "white", linewidth = 0.3 ) + scale_fill_manual( values = c("TRUE" = "#e6550d", "FALSE" = "#3182bd"), labels = c("TRUE" = "女性薪酬占优", "FALSE" = "男性薪酬占优") ) + scale_y_continuous(limits = shared_ylim, expand = expansion(mult = c(0, 0.05))) + labs(x = "平均时薪差(%)", y = NULL, fill = "差异方向") + theme_bw() + theme(legend.position = "bottom") # 等宽拼图 grid.arrange(p1, p2, nrow = 1, widths = c(1, 1))
关键实现细节
- 分色规则:
after_stat(x > 0)会直接读取分箱后的区间中心值,快速判定该分箱归属正值/负值区间,全程不需要手动拆分正负数据子集 - 刻度对齐:预先完成分箱计数测算后设置统一ylim,相比后续手动指定y值的方式,不会出现因分箱边界差异导致的刻度错位
- 视觉一致性:两张图使用完全相同的色值、刻度规则、字体主题,拼图时可通过
ggpubr::ggarrange的common.legend = TRUE参数合并重复图例,减少视觉干扰
内容的提问来源于stack exchange,提问作者gregV
相关产品推荐
相关产品推荐

