ggplot2如何实现同一月份x轴下并排展示筛选行与全量数据的箱线图
箱线图重叠问题的解决方法
你遇到的同月份两类箱线图完全重叠,核心原因是两个geom_boxplot图层都把Month作为x轴的固定分组位置,没有给两类统计范围分配横向偏移量,导致两个箱线图完全落在同一个x坐标点上。
推荐实现方式(标准化ggplot逻辑)
不要拆分两个独立图层绘制,先将两类统计范围的数据集合并为长格式结构,新增一列标识每条数据所属的统计类别,再通过position_dodge自动实现同月份下的并排展示,代码可直接复用:
- 数据整理步骤
library(dplyr) library(ggplot2) # 合并两类统计范围的数据,新增分类标识列 df_tidy <- bind_rows( # 全量样本子集 df %>% mutate(data_type = "Chamber"), # B字段过滤后的子集 df %>% filter(B == 1) %>% mutate(data_type = "Chamber_no fire") ) - 绘图代码
ggplot(df_tidy, aes(x = Month, y = A, fill = data_type)) + geom_boxplot( # *position_dodge* 是核心控制参数,可通过width调整同月份下两个箱线图的并排间距 position = position_dodge(width = 0.8), outlier.shape = 16 ) + theme_bw() + theme(panel.grid.major = element_blank()) + scale_x_continuous(breaks=seq(2,12,1), minor_breaks = NULL) + geom_hline(yintercept = 0, linetype="dotted") + # 可根据需要自定义图例名称和配色 scale_fill_manual( values = c("Chamber" = "#619CFF", "Chamber_no fire" = "#F8766D"), name = "统计范围" ) ggsave("sate_meas_O3_NOx_5km_nofire.png", width = 6, height = 4, units = "in")
兼容原有代码的实现方式
如果不想调整原有数据结构,可以直接手动给两个图层的x坐标添加固定偏移量,实现同月份下的位置错开,不需要合并数据集:
offset <- 0.4 # 控制两个箱线图的横向间距,数值越大间距越宽 ggplot() + # 过滤后的样本子集,x坐标向左偏移 geom_boxplot( data = df %>% filter(B == 1), aes(x = Month - offset/2, y = A, fill = "Chamber_no fire"), position = "identity", outlier.shape = 16 ) + # 全量样本子集,x坐标向右偏移 geom_boxplot( data = df, aes(x = Month + offset/2, y = A, fill = "Chamber"), position = "identity", outlier.shape = 16 ) + # 将x轴刻度位置还原为整月值,避免偏移后刻度错位 scale_x_continuous( breaks = seq(2,12,1), minor_breaks = NULL, name = "Month" ) + scale_fill_manual( values = c("Chamber" = "#619CFF", "Chamber_no fire" = "#F8766D"), name = "统计范围" ) + theme_bw() + theme(panel.grid.major = element_blank()) + geom_hline(yintercept = 0, linetype="dotted")
原有代码的参数修正提示
- 原代码中
outlier.shape = T为无效参数,shape的合法输入是0-25的数值编码,传入逻辑值会被强制转换为数值1,显示为空心小三角,不符合常规离群点的展示需求 - 原代码中
minor_breaks = F为无效参数,需将次刻度关闭的参数值设为NULL - 原aes中手动添加的
group=Month在分类映射下属于冗余参数,ggplot会根据fill的分类自动识别分组
内容的提问来源于stack exchange,提问作者user13795242
相关产品推荐
相关产品推荐

