ggplot2设置主Y轴指定刻度后次坐标轴消失的解决方法
解决方法
问题出在你错误地用ylim=c(0, 90, 180, 270, 360)来设置刻度——ylim参数仅接受两个值(轴的上下限),传入多个值会导致主Y轴范围异常,进而让次坐标轴无法正常显示。
要指定主Y轴的刻度,应该在scale_y_continuous中使用breaks参数,同时配合limits明确轴的范围(确保和刻度匹配)。修改后的关键代码如下:
p <- p + scale_y_continuous( breaks = c(0, 90, 180, 270, 360), # 指定主Y轴刻度 limits = c(0, 360), # 主Y轴范围 sec.axis = sec_axis(~./25, name = "wind speed (m/s)") # 修正拼写和单位 )
完整修改后的代码
p <- ggplot(df, aes(x = date)) p <- p + geom_line(aes(y = wd, colour = "wind direction")) p <- p + geom_line(aes(y = ws*25, colour = "wind speed")) # 修正主Y轴刻度设置,同时修正次轴名称的拼写和单位 p <- p + scale_y_continuous( breaks = c(0, 90, 180, 270, 360), limits = c(0, 360), sec.axis = sec_axis(~./25, name = "wind speed (m/s)") ) p <- p + scale_colour_manual(values = c("#e377c2", "#7f7f7f")) p <- p + labs(y = "wind direction (°)") p <- p + theme(text = element_text(size = 12)) + xlab("") + theme_light() + theme(legend.position = "null") + theme(axis.text.x=element_blank()) p
另外注意修正了次轴名称里的拼写错误(spped改为speed)和单位格式(ms改为m/s),让图表标注更准确。
内容的提问来源于stack exchange,提问作者Morshad Ahmed
相关产品推荐
相关产品推荐

