ggplot2使用ggbreak后零点聚集问题及x轴无数据区间删除需求
解决ggbreak后各组零点聚集的问题
问题原因
使用scale_x_break(c(1,11))隐藏x轴1-11区间后,x轴上0和12的视觉距离被大幅拉近,导致不同Isolate组在time=0处的点完全重叠聚集。
解决方案:用position_dodge横向分散同x值的组元素
在geom_point和geom_line中添加position = position_dodge(width = 0.5)参数,让同一时间点(这里特指0点)的不同组的点和线横向分散开,避免重叠。
修改后的完整代码:
plot <- ggplot(bgse_lmean, aes(time_h)) + geom_point(aes(y = Conc, shape = Isolate, col = Isolate, group = Isolate), size = 2.5, position = position_dodge(width = 0.5))+ geom_line(aes(y = Conc, group= Isolate, col = Isolate), position = position_dodge(width = 0.5))+ scale_x_continuous(breaks=c(0,12, 16, 20, 24))+ xlab("Time (h)") + ylab("Conc mg/ml") + scale_color_brewer(palette = "Set1") + facet_wrap(parameters~., strip.position = "top", nrow = 3) p2 <- plot + scale_x_break(c(1,11)) p2
调整建议
- 可以根据图形实际效果调整
width参数的数值(比如0.3或0.7),找到最适合的分散距离。 - 如果不想让线也分散,只需要给
geom_point添加position_dodge即可,但建议线和点保持一致的偏移,保证图形逻辑连贯。
内容的提问来源于stack exchange,提问作者Buddhiman Tamang
相关产品推荐
相关产品推荐

