Reputation: 19
I would like a line plot in R of the days a bird spent away from its nest. I have missing data that is making it difficult to show the general trend. I want to replace the line for the days that I don't have information for with a dotted line. I have absolutely no idea how to do this. Is it possible to do in 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
My attempt:
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))
Upvotes: 1
Views: 463
Reputation: 32426
Here is a way using diff
to make a variable determining if a sequence is missing. Note that I renamed your data to 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))
)
For the ggplot version, you can make another data.frame with the lagged variables used above,
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()
Upvotes: 2