ggplot绘图如何隐藏无数据的10-12月且保留月份正确排序
问题原因
你在代码中指定scale_x_discrete(limits = month.name)时,R内置的month.name是包含1-12月完整月份名称的全局向量,即便你已经提前过滤了10-12月的数据集,ggplot仍会按照你指定的完整分类范围显示所有12个月份的X轴刻度。
解决方案
直接修改scale_x_discrete的limits参数,仅指定1-9月的范围即可,修改后的绘图代码如下:
ggplot(monthly_trips)+ geom_bar(aes(x= month, fill= member_casual),position = "dodge")+ labs(title = "月度骑行量:会员 vs 散客",caption = "数据来源:Motivate International INC.")+ theme(axis.text.x = element_text(angle = 50,hjust = 1))+ # 仅取前9个月份作为X轴展示范围 scale_x_discrete(limits = month.name[1:9])
可选优化方案
如果后续需要频繁操作月份维度,可在数据预处理阶段直接将month列转换为有序因子,固定展示顺序后不需要再在ggplot中额外指定limits:
# 预处理步骤:过滤+转换有序因子,用%in%简化多条件判断逻辑 monthly_trips <- data_trip_cleaned%>% filter(month %in% month.name[1:9]) %>% mutate(month = factor(month, levels = month.name[1:9])) # 绘图代码无需再指定scale_x_discrete的顺序参数 ggplot(monthly_trips)+ geom_bar(aes(x= month, fill= member_casual),position = "dodge")+ labs(title = "月度骑行量:会员 vs 散客",caption = "数据来源:Motivate International INC.")+ theme(axis.text.x = element_text(angle = 50,hjust = 1))
内容的提问来源于stack exchange,提问作者Frans_Gel
相关产品推荐
相关产品推荐

