ggplot2柱状图仅显示误差条、柱体不显示的问题求助
问题原因与解决方案
问题根源
你遇到的柱体不显示、仅误差条可见的问题,核心原因是scale_y_continuous(limits=c(1,5))的设置:geom_col默认从y=0开始绘制柱体,而柱体的底部区间(0到1)超出了设定的y轴范围,ggplot因此移除了这两个柱体的图形元素;而误差条的数值范围(2.9~3.75)完全在1-5区间内,所以正常显示。
解决方案
方案1:调整y轴下限为0,完整显示柱体
修改scale_y_continuous的下限为0,让柱体的全部高度都落在y轴范围内:
graph5<-ggplot(plr_sum2, aes(x=Friend, y=Ranking) ) + geom_col(fill="lightblue") + theme_bw()+ geom_errorbar( aes(x=Friend, ymin=Ranking-se, ymax=Ranking+se, width=0.2), colour="black", alpha=0.9, size=0.5)+ labs(y = "Social Preference", x = "Register Choice")+ scale_x_discrete(breaks=c("Correct","Incorrect"))+ scale_y_continuous(limits=c(0,5)) # 将y轴下限改为0 graph5
方案2:用coord_cartesian裁切视图(保留y轴1-5显示)
如果想维持y轴从1开始的显示,可以用coord_cartesian替代scale_y_continuous——它仅缩放视图范围,不会删除超出范围的数据,柱体的上半部分会正常显示:
graph5<-ggplot(plr_sum2, aes(x=Friend, y=Ranking) ) + geom_col(fill="lightblue") + theme_bw()+ geom_errorbar( aes(x=Friend, ymin=Ranking-se, ymax=Ranking+se, width=0.2), colour="black", alpha=0.9, size=0.5)+ labs(y = "Social Preference", x = "Register Choice")+ scale_x_discrete(breaks=c("Correct","Incorrect"))+ coord_cartesian(ylim=c(1,5)) # 替换为coord_cartesian设置视图范围 graph5
额外检查
可以用str(plr_sum2)确认Ranking列是数值型,避免因数据类型错误导致的绘图问题。
内容的提问来源于stack exchange,提问作者Zoe Liberman
相关产品推荐
相关产品推荐

