You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用scale_y_discrete后geom_crossbar的y轴间距不均,如何调整?

问题解决方法

你的问题出在scale_y_discrete的limits参数用了包含重复值的原始id列,导致y轴把重复的B当成了多个离散水平,从而拉大了对应间距。解决核心是确保limits里的每个id仅出现一次,具体有两种方法:

方法1:修正scale_y_discrete的limits参数

直接使用去重后的id进行排序,避免重复值干扰y轴离散水平:

df <- data.frame(id=c("A","B","B","B","C"),low=c(1,2,4,9,1),high=c(2,3,7,12,4))
g1 <- ggplot(df, aes(x=low, y=id)) + 
  geom_crossbar(aes(xmin=low, xmax=high), stat="identity", show.legend = NA)
# 去重后按降序排序,作为y轴离散水平
g1 + scale_y_discrete(limits = rev(sort(unique(df$id))))

方法2:提前将id转为有序因子

先把id列转为因子并指定排序后的水平,ggplot会自动按因子水平渲染y轴,无需额外设置scale:

df <- data.frame(id=c("A","B","B","B","C"),low=c(1,2,4,9,1),high=c(2,3,7,12,4))
# 设置因子水平为降序的唯一id值
df$id <- factor(df$id, levels = rev(sort(unique(df$id))))
g1 <- ggplot(df, aes(x=low, y=id)) + 
  geom_crossbar(aes(xmin=low, xmax=high), stat="identity", show.legend = NA)
g1

两种方法都能让每个id在y轴上保持相等的间距,同时保留每个id对应的所有crossbar图形。

内容的提问来源于stack exchange,提问作者Wansong Xu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:15:49