ggplot直方图首个条形未对齐左轴的问题求助
问题原因与解决办法
核心问题分析
第一个条形未触碰左轴的根源是ggplot2默认分箱逻辑没有对齐你设定的x轴左边界xlimit(1000000)。你之前尝试的boundary=0方向错误,应该把边界对齐到数据起始点xlimit而非0。
另外代码存在两处笔误会导致比例计算错误:
nrow(funique_cd)应改为nrow(fprofiles_over_x)(你定义的女性子集是fprofiles_over_x,不存在funique_cd对象)nrow(munique_cd)应改为nrow(mprofiles_over_x)(同理,男性子集是mprofiles_over_x)
修复后的代码
xlimit = 1000000 upper = max(unique_cd$Total_Medicare_Payment) mprofiles_over_x <- unique_cd |> filter(Total_Medicare_Payment >= xlimit, Gender == "M") fprofiles_over_x <- unique_cd |> filter(Total_Medicare_Payment >= xlimit, Gender == "F") # 计算分箱宽度,确保从xlimit开始生成75个分箱 bin_width <- (12000000 - xlimit)/75 ggplot() + geom_histogram(data = fprofiles_over_x, aes(x = Total_Medicare_Payment, y = after_stat(count / nrow(fprofiles_over_x)), fill = "Female"), color = "black", binwidth = bin_width, # 使用计算好的固定分箱宽度 boundary = xlimit, # 强制分箱左边界对齐xlimit alpha = 0.3, size = 0.1, na.rm = TRUE) + geom_histogram(data = mprofiles_over_x, aes(x = Total_Medicare_Payment, y = after_stat(count / nrow(mprofiles_over_x)), fill = "Male"), color = "black", binwidth = bin_width, boundary = xlimit, alpha = 0.3, size = 0.1, na.rm = TRUE) + scale_x_continuous(limits = c(xlimit, 12000000), breaks = seq(xlimit, 12000000, by = 3000000), labels = scales::comma) + scale_y_continuous(limits = c(0, .001), breaks = seq(0, .001, by = .00025), labels = scales::percent) + labs(x = "Total Medicare Payment (2017-2021)", y = "% Radiologists") + scale_fill_manual(values = c("Female" = "orange", "Male" = "lightblue"), name = "Gender") + theme_minimal() + theme( legend.position = c(.95, .95), legend.justification = c("right", "top"), legend.box.just = c("right", "center"), legend.box.background = element_rect(linewidth=.1), legend.box.margin = margin(-4, 1, 1, 1), legend.title=element_blank(), legend.text = element_text(size = 7), legend.key.width = unit(.4, "cm"), legend.key.height = unit(0.4, "cm") )
关键修改说明
- 修正比例计算笔误:将分母替换为对应子集的行数,保证百分比统计准确。
- 手动计算分箱宽度:基于x轴范围和指定的75个分箱,生成固定宽度的分箱,避免ggplot自动分箱的偏移。
- 设置
boundary = xlimit:强制分箱左边界对齐到x轴起始点1000000,让第一个条形的左边缘完全触碰左轴。
如果不想手动计算binwidth,也可以保留bins=75,但必须加上boundary=xlimit,不过手动计算binwidth能让分箱逻辑更可控,避免不同数据集下的分箱偏移。
内容的提问来源于stack exchange,提问作者Chris Lee
相关产品推荐
相关产品推荐

