ggplot line graph with NA values

前端 未结 3 2118
眼角桃花
眼角桃花 2020-12-31 12:08

I\'m having with trouble with ggplot trying to plot 2 incomplete time series on the same graph where the y data does not have the same values on the x-axis (year) - NAs are

3条回答
  •  执念已碎
    2020-12-31 12:26

    You can remove them with na.omit:

    library(ggplot2)
    #use na.omit below
    ggplot(na.omit(test), aes(x=YEAR)) + 
      geom_line(aes(y = A1), size=0.43, colour="red") +  
      geom_line(aes(y = A2), size=0.43, colour="green") +
      xlab("Year") + ylab("Percent") +
      scale_x_continuous(limits=c(1935, 1995), breaks = seq(1935, 1995, 5),
                         expand = c(0, 0)) + 
      scale_y_continuous(limits=c(0,50), breaks=seq(0, 50, 10), expand = c(0, 0))
    

    enter image description here

    EDIT

    Using 2 separate data.frames with na.omit:

    #test1 and test2 need to have the same column names
    test1 <- test[1:2]
    test2 <- tes[c(1,3)]
    colnames(test2) <- c('YEAR','A1')
    
    library(ggplot2)
    ggplot(NULL, aes(y = A1, x = YEAR)) + 
      geom_line(data = na.omit(test1), size=0.43, colour="red") +  
      geom_line(data = na.omit(test2), size=0.43, colour="green") +
      xlab("Year") + ylab("Percent") +
      scale_x_continuous(limits=c(1935, 1995), breaks = seq(1935, 1995, 5),
                         expand = c(0, 0)) + 
      scale_y_continuous(limits=c(0,50), breaks=seq(0, 50, 10), expand = c(0, 0))
    

    enter image description here

提交回复
热议问题