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

ggplot2使用position_dodge时如何让单根条形柱居中显示

解决方法

单根分组柱靠左是因为position_dodge的默认避让宽度和柱子自身宽度不匹配,只需同步调整两个width参数即可实现居中:

ggplot(data = combo1, aes(x = Age_Year, fill = Tactic)) + 
    # 两处width参数需保持数值一致,可根据视觉需求调整具体数值
    geom_bar(width = 0.7, position = position_dodge(width = 0.7, preserve = 'single')) + 
    theme_classic() + 
    labs(x = "Age (years)", y = "Counts of Fish", show.legend = FALSE)+
    theme(legend.position = "none")+
    scale_fill_manual("legend",  values = c("Migr" = "skyblue", "OcRes" = "pale green", "EstRes" = "pink"))

可选优化

如果不需要在x轴展示无样本的年龄刻度,可以将x轴变量转为因子,避免出现空刻度,展示更紧凑:只需将aes中的x参数改为x = factor(Age_Year)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:54:05