ggplot绘图下方莫名出现0,如何去除?
解决方案:移除ggplot x轴下方的莫名0
问题根源
你代码里的scale_x_discrete函数存在语法错误:expand = c(0,.1)被多余的括号包裹,写成了(expand = c(0,.1))。这个错误会让R解析出意外输出,最终在x轴下方显示出0。
修正后的代码
把两个图表代码里scale_x_discrete行中的多余括号去掉即可:
修正后的output1代码
output1 <- ggplot(data=SP22_SP23, aes(x=semesters, y=UG_classif, group=1)) + geom_line( aes(y=UG_classif), color="mediumaquamarine")+ geom_point() + scale_x_discrete(limits = c("SP22", "SUM22", "FA22", "SP23"), expand = c(0,.1)) + # 移除expand外的括号 scale_y_continuous(n.breaks = 10, limits = c(500, 3500)) + labs(title = "Undergraduate Enrollment:", subtitle= "Sp'22 through Sp'23\n", x = NULL, y = "Student Count") + theme_minimal() + removeGridX()
修正后的output2代码
output2 <- ggplot(data=SP22_SP23, aes(x=semesters, y=NDseeking, group=1)) + geom_line( aes(y=NDseeking), color="tan3")+ geom_point() + scale_x_discrete(limits = c("SP22", "SUM22", "FA22", "SP23"), expand = c(0,.1)) + # 移除expand外的括号 scale_y_continuous(n.breaks = 10, limits = c(0, 400)) + labs(title = "Non-degree Seeking Enrollment:", subtitle= "Sp'22 through Sp'23\n", x=NULL, y = "Student Count") + theme(axis.title.x=element_blank()) + theme_minimal() + removeGridX()
补充说明
- 这个语法错误会让R将
(expand = c(0,.1))解析为赋值表达式,其返回值是c(0,.1),scale_x_discrete会把这个额外的未命名参数错误处理,最终导致x轴下方出现0。 - 修正后,既能保留你需要的x轴刻度(SP22等),也能移除莫名的0,同时之前设置的
x=NULL和axis.title.x=element_blank()也能正常生效。
内容的提问来源于stack exchange,提问作者RKeithL
相关产品推荐
相关产品推荐

