I have population simulation data with 200 replications of 50, 1 year iterations. I want to plot all 200 trajectories as lines (y=population size, x=year) on the same plot. The following code meets this need...
baseline<-read.csv("C:\\Users\\Chelsea Mitchell\\Desktop\\Poster materials\\chinook baseline raw.csv", header=T)
plot(baseline$time.step..year[1:50],
baseline$pop.size[1:50], type="l", main="baseline model"
, xlab= "Year", ylab= "Population size", ylim= c(0,2e+08))
for (i in 2:(length(baseline$time.step..year)/50))
{lines(baseline$time.step..year[(1+(i-1)*50):(i*50)],
baseline$pop.size[(1+(i-1)*50):(i*50)])}
image of appropriate plot without extinction
But in some cases, the population goes extinct, and trajectories stop before year 50. How can I tell the for loop to stop the trajectory line before the following simiulation data starts again at year 1?
image of problem plot with extinction
Here is a constructed, simple version of the data and code with the same issue. The maximum number of years is 10, so the for loop plots trajectory lines for "year" sequences of 1:10. In cases where pop.size reaches 0, the replications stop, so the trajectory plotting should also stop.
rep <- c(1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3)
year <- c(1,2,3,4,1,2,3,4,5,6,1,2,3,4,5,6,7,8,9,10)
pop.size <- c(526,120,165,0,634,637,452,130,189,0,599,436,320,245,336,225,134,37,87,0)
extinct.pop <- data.frame(rep,year,pop.size)
plot(extinct.pop$year[1:10], extinct.pop$pop.size[1:10],
type="l", xlim= c(0,10))
for (i in 2:(length(extinct.pop$year)/10)){
lines(extinct.pop$year[(1+(i-1)*10):(i*10)],
extinct.pop$pop.size[(1+(i-1)*10):(i*10)])}
Thank you for your help!