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
相关产品推荐
相关产品推荐

