How can I get my points to connect in a plot and show a trend with NA values in data?

前端 未结 2 1962
逝去的感伤
逝去的感伤 2021-01-28 16:12

I have a basic set of data, where I measure concentration over time for 24 months. Some months have not been sampled, so there are 6 NA values in my list.

相关标签:
2条回答
  • 2021-01-28 16:45

    Using data from Gwang-Jin Kim's answer and the suggestion of dashing the lines where NAs exist, here's a redo. I'll keep the previous answer below.

    lines (and therefore plot(..., type="l")) requires that lty be the same for all components, so to get dashed sections you need to use segments over each point-to-point.

    For extra credit, I'm including red dots along the x-axis where data was dropped at the time the NA value exists.

    df <- data.frame(time=c(-1, 0, 1:24),
                     pt=c(7.0, 6.9, NA, 5.5, 5, 3, 14, NA, 23, NA, 14.5, 7, 9, NA,
                          11, 8, 5.2, 5.3, NA, 5, 3, NA, 1.5, NA, NA, 2))
    len <- nrow(df)
    notna <- !is.na(df$pt)
    df$dashes <- c(TRUE, !notna[-len])
    df0 <- df[notna,]
    len0 <- nrow(df0)
    
    plot(pt ~ time, data=df0,
         type="p", pch=16, col="blue", 
         xlab="Time (months) relative to implant", ylab="Concentration (ng/ml)", 
         main="Concentration Overtime", 
         xaxt='n')
    points(df$time, par('usr')[3] * is.na(df$pt), pch = 16, col = "red")
    ign <- Map(segments, df0$time[-len0], df0$pt[-len0],
               df0$time[-1], df0$pt[-1],
               1, 1+df0$dashes[-1])
    axis(1, at=seq(-1, 24, by=1))
    


    Here's a guess:

    notna <- !is.na(pt)
    plot(time[notna], pt[notna], type="o", pch=16, col="blue", 
        xlab="Time (months) relative to implant", ylab="Concentration (ng/ml)", 
        main="Concentration Overtime", 
        xaxt='n')
        axis(1, at=seq(-1, 24, by=1))
    

    One problem in your second code

    plot(na.omit(pt), ...)
    

    is that you have not included time, so R naturally fills in with seq_along(na.omit(pt)) (almost the same as 1:length(na.omit(pt))), which for you is losing your time data. By using [notna] to subset both vectors, we are preserving the data you need for the plot.

    0 讨论(0)
  • 2021-01-28 16:57
    df <- data.frame(time=c(-1, 0, 1:24),
    pt=c(7.0, 6.9, NA, 5.5, 5, 3, 14, NA, 23, NA, 14.5, 7, 9, NA, 11, 8, 5.2, 5.3, NA, 5, 3, NA, 1.5, NA, NA, 2))
    
    png("test.png")
    plot(pt~time, type="o", data=na.omit(data.frame(df)),
         pch=16, col="blue",
         xlab="Time (months) relative to implant",
         ylab="Concentration (ng/ml)",
         main="Concentration Overtime",
         xlim=c(-1, 24),
         xaxt='n')
    axis(1, at=seq(-1, 24, by=1))
    dev.off()
    

    0 讨论(0)
提交回复
热议问题