将散点图线与 R 中的缺失值连接

问题描述 投票:0回答:1

有没有办法创建一个散点图,其中的线连接所有点,即使数据集中缺少值? 例如,下面的图现在没有连接所有 series1 点的线,因为缺少值。有办法连接它们吗?这个问题的唯一其他解决方案是使用基本 R 绘图()函数而不是 ggplot 来解决。

#generate fake dataset with three columns 'x', 'value', and 'variable'
data <- data.frame(x=rep(1:5, 3),
                   value=c(2,4,NA,6,2,3,5,4,3,6,9,7,4,3,5), 
                   variable=rep(paste0('series', 1:3), each=5))
data
#plot all three series on the same chart using geom_line()
ggplot(data = data, aes(x=x, y=value, group =variable)) + geom_line(colour = "black") + geom_point(aes(shape=variable, color=variable, fill = variable), size=2) +
  scale_shape_manual(values=c(21, 22, 23))+
  scale_color_manual(values=c('black','black', 'black'))+
  scale_fill_manual(values= c('#999999','#E69F00', '#56B4E9')) +
  theme_classic() + theme(panel.border = element_rect(colour = "black", fill=NA, size=1), legend.justification=c(1,1), legend.position=c(1,1)  ) + geom_vline(xintercept=3, linetype="dotted")
                           

r ggplot2 scatter-plot
1个回答
1
投票

您需要将不带

NA
值的数据框副本传递给
geom_line
。比如:

ggplot(data = data, aes(x, value, group = variable, fill = variable)) + 
  geom_line(colour = "black", data = data[complete.cases(data),]) + 
  geom_point(aes(shape = variable), color = "black", size = 2) +
  geom_vline(xintercept = 3, linetype = "dotted")+
  scale_shape_manual(values = c(21, 22, 23)) +
  scale_fill_manual(values = c('#999999','#E69F00', '#56B4E9')) +
  theme_classic() + 
  theme(panel.border = element_rect(colour = "black", fill = NA, linewidth = 1), 
        legend.justification = c(1, 1), 
        legend.position = c(1, 1)) 

© www.soinside.com 2019 - 2024. All rights reserved.