You need to enable JavaScript to run this app. 使用ggplot绘制负值区分配色、共享统一y轴刻度的双直方图
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.25 23:45:05