R语言ggplot2如何解决geom_dotplot点图与x轴分类标签不对齐的问题
问题描述
- 用ggplot2生成点图时,除第一个实验类别外,其余类别的堆叠点均未与对应的x轴实验标签对齐
- 运行代码时收到自动分箱的警告提示
原始绘图代码
emibc_plot <- ggplot(emibc, aes(x = experiment, y = value, fill = model)) + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.title=element_blank()) + scale_y_continuous(breaks = sort(c(seq(min(emibc$value), max(emibc$value), length.out=5), 0)), label= function(x) {ifelse(x==0, "0", scales::scientific_format(digits = 3)(x))}) + geom_dotplot(binaxis = "y", stackdir = "center", stackgroups=TRUE, binpositions="all", dotsize = 0.5)
数据集(dput输出)
structure(list(model = c("CESM", "E3SM", "GISS", "MIROC", "CESM", "E3SM", "GISS", "MIROC", "CESM", "E3SM", "GISS", "MIROC", "CESM", "E3SM", "MIROC", "CESM", "E3SM", "GISS", "MIROC"), experiment = c("bc_no_seas", "bc_no_seas", "bc_no_seas", "bc_no_seas", "high_SO4", "high_SO4", "high_SO4", "high_SO4", "no_SO4", "no_SO4", "no_SO4", "no_SO4", "SO2_at_height", "SO2_at_height", "SO2_at_height", "SO2_no_season", "SO2_no_season", "SO2_no_season", "SO2_no_season"), value = c(2.13359e-16, 2.13549e-16, 1.04680e-17, 2.86707e-16, 3.97356e-20, 1.77632e-20, 0, 0, 2.22483e-20, 1.17037e-20, 0, 0, 2.51571e-20, 9.81121e-21, 0, 1.67484e-20, 1.46975e-20, 0, 0)), row.names = c(NA, -19L), class = c("tbl_df", "tbl", "data.frame"))
生成的原始图表

运行警告
运行时收到的提示:
`stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
问题原因
- 点与x轴标签不对齐的核心诱因是*
binpositions = "all"与stackgroups = TRUE*的参数组合:前者会让分箱统计逻辑基于全数据集的y值生成统一的bin位置,搭配跨模型堆叠的参数后,会导致堆叠的点被错误对齐到首个x类别的中心,而非各自所属的x实验类别位置。 - 分箱警告来自未手动指定
binwidth参数,代码默认按30个分箱自动计算y方向的分箱宽度。
修正方案
- 移除
binpositions = "all"参数,使用默认的binpositions = "by group"逻辑,让每个x类别下的堆叠点自动对齐到对应x标签的中心位置。 - 手动指定
binwidth参数(可根据y值范围调整,示例中按当前数据集的y值范围设置为5e-18,可根据可视化效果微调),既消除分箱警告,也能保证所有x组的y方向分箱宽度统一,实现不同组同y值点水平对齐的效果。
修正后代码
emibc_plot <- ggplot(emibc, aes(x = experiment, y = value, fill = model)) + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.title=element_blank()) + scale_y_continuous(breaks = sort(c(seq(min(emibc$value), max(emibc$value), length.out=5), 0)), label= function(x) {ifelse(x==0, "0", scales::scientific_format(digits = 3)(x))}) + geom_dotplot(binaxis = "y", stackdir = "center", stackgroups=TRUE, binwidth = 5e-18, dotsize = 0.5)
内容的提问来源于stack exchange,提问作者hahsan1
相关产品推荐
相关产品推荐

