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

ggplot2 geom_bar分面分组条形图Y轴数值与排序异常问题求助

问题原因

  • 使用cbind()拼接不同类型向量时,所有列会被强制转换为字符型,后续构造数据框时计数列No未被识别为数值类型,ggplot映射y轴高度时按照字符字典序而非实际数值大小计算,导致数值为900的条高异常高于数值为1100的条。
  • 重叠阈值列overlap转为字符型后默认生成的因子顺序不符合预期,也会导致并列条形的排列顺序错乱。

解决代码

直接调整数据框构造逻辑,明确指定列类型和阈值排序即可:

library(ggplot2)
overlap <- c(0.3,0.5,0.8,1.0,
             0.3,0.5,0.8,1.0,
             0.3,0.5,0.8,1.0,
             0.3,0.5,0.8,1.0,
             0.3,0.5,0.8,1.0,
             0.3,0.5,0.8,1.0)

region <- c("chr_reg","chr_reg","chr_reg","chr_reg",
          "chr_reg","chr_reg","chr_reg","chr_reg",
          "chr_reg","chr_reg","chr_reg","chr_reg",
          "random","random","random","random",
          "random","random","random","random",
          "random","random","random","random")

Element <- c("LINE1","LINE1","LINE1","LINE1",
         "LINE2","LINE2","LINE2","LINE2",
         "LINE3","LINE3","LINE3","LINE3",
         "LINE1","LINE1","LINE1","LINE1",
         "LINE2","LINE2","LINE2","LINE2",
         "LINE3","LINE3","LINE3","LINE3")

No <- c(1100,1000,1000,900,
        3000,3000,2900,2900,
        1900,1500,1700,1500,
        2500,2500,2500,2600,
        5200,5000,5200,5000,
        3500,3000,3500,3600)

# 修正数据框构造逻辑
df_full2 <- data.frame(
  overlap = factor(overlap, levels = c(0.3, 0.5, 0.8, 1.0)),
  Element = Element,
  region = region,
  No = as.numeric(No)
)

# 绘图代码无需修改
ggplot(df_full2,aes(x = region, y = No,fill = overlap)) + 
  geom_bar(stat = "identity", position = "dodge",colour="black")+
  theme_bw() + 
  facet_wrap(~Element)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 16:33:01