使用scale_y_reverse()时如何将geom_area置于折线下方?
问题:反转Y轴后geom_area无法显示在曲线下方
我需要翻转折线图的坐标轴,但要让geom_area始终处于曲线下方,尝试了以下代码:
ggplot(PalmBeachWell, aes(x=Date, y=Depth.to.Water.Below.Land.Surface.in.ft.)) + geom_area(position= "identity", fill='lightblue') + theme_classic() + geom_line(color="blue") + scale_y_reverse()
得到的效果如图所示:
解决方法
问题出在geom_area默认从y=0开始填充,使用scale_y_reverse()反转坐标轴后,y=0会移动到图表顶部,导致填充区域变成曲线到顶部的部分,而非曲线下方。可以用以下两种方法解决:
方法1:反转数值而非坐标轴
直接对y变量取反,再调整刻度标签显示原数值:
ggplot(PalmBeachWell, aes(x=Date, y=-Depth.to.Water.Below.Land.Surface.in.ft.)) + geom_area(fill='lightblue') + theme_classic() + geom_line(color="blue") + scale_y_continuous(labels = function(x) -x)
方法2:用geom_ribbon替代geom_area
指定填充的下限为数据的最小值(反转后会位于坐标轴底部):
# 先获取y变量的最小值 y_min <- min(PalmBeachWell$Depth.to.Water.Below.Land.Surface.in.ft., na.rm = TRUE) ggplot(PalmBeachWell, aes(x=Date, y=Depth.to.Water.Below.Land.Surface.in.ft.)) + geom_ribbon(aes(ymin = y_min, ymax = Depth.to.Water.Below.Land.Surface.in.ft.), fill='lightblue') + theme_classic() + geom_line(color="blue") + scale_y_reverse()
两种方法都能让填充区域显示在曲线下方,同时保持Y轴反转的效果。
内容的提问来源于stack exchange,提问作者paras
相关产品推荐
相关产品推荐

