2015-10-19 55 views
1

我想在一隻鳥從鳥巢中消失的日子的R線圖上。 我有遺漏的數據,很難顯示大致的趨勢。我想用虛線替換沒有信息的日子。我完全不知道如何做到這一點。 R有可能嗎?連接缺失數據的線R

 > time.away.1 
    hrs.away days.rel 
1  0.380  -2 
2  0.950  -1 
3  1.000  0 
4  0.200  1 
5  0.490  12 
6  0.280  13 
7  0.130  14 
8  0.750  20 
9  0.160  21 
10 1.830  22 
11 0.128  26 
12 0.126  27 
13 0.500  28 
14 0.250  31 
15 0.230  32 
16 0.220  33 
17 0.530  40 
18 3.220  41 
19 0.430  42 
20 1.960  45 
21 1.490  46 
22 24.000  56 
23 24.000  57 
24 24.000  58 
25 24.000  59 
26 24.000  60 
27 24.000  61 

我嘗試:

plot(hrs.away ~ days.rel, data=time.away.1, 
    type="o", 
    main="Time Away Relative to Nest Age", 
    ylab="Time spent away", 
    xlab="Days Relative to Initiation", 
    ylim=c(0,4)) 

This is what my graph looks like currently

+0

您可能需要包含您用來製作當前情節的代碼? – jeremycg

+0

這並不是我所擁有的,我找不到我用來製作它的代碼(它在5月份回來了),現在我真的在踢我自己,因爲它沒有保存確切的代碼。但我只是擺弄它的樣子。這幾乎是一回事。 – JennaM

+0

我想用實線表示哪些天有數據,虛線表示哪些數據沒有數據。 – JennaM

回答

2

下面是一個使用diff使變量確定序列缺失的一種方式。請注意,我改名爲您的數據dat

## make the flag variable 
dat$type <- c(TRUE, diff(dat$days.rel) == 1) 

plot(hrs.away ~ days.rel, data=dat, 
    type="p", 
    main="Time Away Relative to Nest Age", 
    ylab="Time spent away", 
    xlab="Days Relative to Initiation", 
    ylim=c(0,4)) 
legend("topright", c("missing", "sampled"), lty=c(2,1)) 

## Add line segments 
len <- nrow(dat) 
with(dat, 
    segments(x0=days.rel[-len], y0=hrs.away[-len], 
       x1=days.rel[-1], y1=hrs.away[-1], 
       lty=ifelse(type[-1], 1, 2), 
       lwd=ifelse(type[-1], 2, 1)) 
    ) 

enter image description here

對於ggplot版本,你可以用上面所用的滯後變量的另一個data.frame,

library(ggplot2) 
dat2 <- with(dat, data.frame(x=days.rel[-len], xend=days.rel[-1], 
          y=hrs.away[-len], yend=hrs.away[-1], 
          type=factor(as.integer(type[-1])))) 

ggplot() + 
    geom_point(data=dat, aes(x=days.rel, y=hrs.away)) + 
    geom_segment(data=dat2, aes(x=x, xend=xend, y=y, yend=yend, lty=type, size=type)) + 
    scale_linetype_manual(values=2:1) + 
    scale_size_manual(values=c(0.5,1)) + 
    ylim(0, 4) + theme_bw() 

enter image description here