ggplot2:用线条连接缺失数据点但不显示缺失点标记
解决方案
要实现Group B的线条连接x=4与x=6的点,同时不在x=5处显示标记,只需调整geom_line参数并控制geom_point的数据源即可,具体代码如下:
library(ggplot2) set.seed(1) x <- rep(seq(1:10), 3) y <- c(runif(10), runif(10) + 1, runif(10) + 2) group <- c(rep("A", 10), rep("B", 10), rep("C", 10)) df <- data.frame(cbind(group, x, y)) df$x <- as.numeric(df$x) df$y <- as.numeric(df$y) df[15,]$y <- NA ggplot(data=df, aes(x=x, y=y, group=group)) + # 忽略NA值,让线条直接连接前后有效点 geom_line(aes(colour=group), na.rm=TRUE)+ # 仅绘制y非缺失的点,自动跳过x=5的标记 geom_point(data=subset(df, !is.na(y)), aes(colour=group, shape=group))+ scale_shape_manual(values = c(1:3)) + theme(legend.position="bottom")
关键说明
geom_line(na.rm=TRUE):默认情况下geom_line遇到NA会断开线条,设置该参数后会忽略缺失值,直接连接前后的有效数据点,实现Group B线条跨过x=5的效果。geom_point(data=subset(df, !is.na(y))):通过子集筛选仅保留y非缺失的行,确保x=5处不会显示Group B的三角形标记。
内容的提问来源于stack exchange,提问作者Stephen Clark
相关产品推荐
相关产品推荐

