ggplot双Y轴下geom_line转geom_area不显示问题求助
解决ggplot副Y轴用geom_area展示潮汐高度的问题
问题原因分析
你尝试的代码中geom_area未正常显示,核心原因有两个:
- 继承了全局
aes中的color=Site和group=Site,潮汐数据按站点分组后无法正确填充面积 - 图层顺序错误,
geom_area放在pH折线之后被完全遮挡
修正后的代码
#Creating pH Time series plots both sites ggplot(data = RB_EOS, aes( x = Time, y = pH_corrected_average, color = Site, group = Site )) + # 把geom_area放在最底层,取消站点分组继承 geom_area(aes(y = 7.55 + Tidal_Depth_ft * 0.075, group = NULL), fill = "lightblue", alpha = 0.3) + geom_line() + geom_line(aes(y = 7.55 + Tidal_Depth_ft * 0.075), linetype = "dotdash", color = "darkblue") + scale_y_continuous( name = "pH", limits = c(7.55, 7.85), breaks = seq(7.55, 7.85, 0.05), sec.axis = sec_axis( ~ (. - 7.55) / 0.075, name = "Tidal Height (ft)", breaks = seq(0, 4, 1)) ) + geom_point() + facet_wrap(~ Week, nrow = 3) + theme_bw(base_size = 13) + theme(legend.position = "top") + ggtitle("pH Tidal Trends") + labs(subtitle = "Summer 2022") + xlab("Time (PST)") + ylab("pH") + scale_x_discrete(guide = guide_axis(angle = 90))
关键修改说明
- 图层顺序:将
geom_area移到最前面,作为背景层避免遮挡pH折线和点 - 取消分组继承:在
geom_area的aes中设置group = NULL,潮汐高度不需要按站点分组 - 填充样式:设置
fill颜色和alpha透明度,平衡潮汐趋势展示与pH数据可读性 - 潮汐折线独立配色:给点虚线单独设置颜色,避免与站点颜色混淆
内容的提问来源于stack exchange,提问作者user21484718
相关产品推荐
相关产品推荐

