-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathplotFunction.r
5039 lines (4220 loc) · 235 KB
/
plotFunction.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Plotting methods for the MizerSim class
library(gridBase) # to get grid.newpage
# Biomass through time
#' Plot the biomass of each species through time
#'
#' After running a projection, the biomass of each species can be plotted against time. The biomass is calculated within user defined size limits (see \code{\link{getBiomass}}).
#' This plot is pretty easy to do by hand. It just gets the biomass using the \code{\link{getBiomass}} method and plots using the ggplot2 package. You can then fiddle about with colours and linetypes etc. Just look at the source code for details.
plotBiomass <- function(object, print_it=TRUE, start_time=as.numeric(dimnames(object@n)[[1]][1]), end_time = as.numeric(dimnames(object@n)[[1]][dim(object@n)[1]]), ...){
b <- getBiomass(object, ...)
names(dimnames(b))[names(dimnames(b))=="sp"] <- "Species"
if(start_time >= end_time){
stop("start_time must be less than end_time")
}
b <- b[(as.numeric(dimnames(b)[[1]]) >= start_time) & (as.numeric(dimnames(b)[[1]]) <= end_time),,drop=FALSE]
bm <- melt(b)
# Force Species column to be a character (if numbers used - may be interpreted as integer and hence continuous)
bm$species <- as.character(bm$species)
# Due to log10, need to set a minimum value, seems like a feature in ggplot
min_value <- 1e-300
bm <- bm[bm$value >= min_value,]
p <- ggplot(bm) +
geom_line(aes(x=time,y=value, colour=species, linetype=species)) +
scale_y_continuous(trans="log10", name="Biomass") +
scale_x_continuous(name="Time") +
theme(legend.title=element_text(),panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"),legend.position="none",
legend.justification=c(1,1),legend.key = element_rect(fill = "white"))+
ggtitle(NULL)
if (nrow(object@params@species_params)>12){
p <- ggplot(bm) + geom_line(aes(x=time,y=value, group=species)) + scale_y_continuous(trans="log10", name="Biomass") + scale_x_continuous(name="Time")
}
if (print_it)
print(p)
return(p)
}
#---------------------------------------------------------------------------------------------------------------------
#' Plot the total yield of each species through time
#'
#' After running a projection, the total yield of each species across all
#' fishing gears can be plotted against time.
#' This plot is pretty easy to do by hand. It just gets the biomass using the \code{\link{getYield}} method and plots using the ggplot2 package. You can then fiddle about with colours and linetypes etc. Just look at the source code for details.
plotYield <- function(object, print_it = TRUE, ...){
y <- getYield(object, ...)
names(dimnames(y))[names(dimnames(y))=="sp"] <- "Species"
ym <- melt(y)
p <- ggplot(ym) + geom_line(aes(x=time,y=value, colour=Species, linetype=Species)) + scale_y_continuous(trans="log10", name="Yield") + scale_x_continuous(name="Time")
if (nrow(object@params@species_params)>12){
p <- ggplot(ym) + geom_line(aes(x=time,y=value, group=Species)) + scale_y_continuous(trans="log10", name="Yield") + scale_x_continuous(name="Time")
}
if (print_it)
print(p)
return(p)
}
#---------------------------------------------------------------------------------------------------------------------
#' Plot the total yield of each species by gear through time
#'
#' After running a projection, the total yield of each species by
#' fishing gear can be plotted against time.
#' This plot is pretty easy to do by hand. It just gets the biomass using the \code{\link{getYieldGear}} method and plots using the ggplot2 package. You can then fiddle about with colours and linetypes etc. Just look at the source code for details.
plotYieldGear <- function(object, print_it=TRUE, ...){
y <- getYieldGear(object, ...)
names(dimnames(y))[names(dimnames(y))=="sp"] <- "Species"
ym <- melt(y)
p <- ggplot(ym) + geom_line(aes(x=time,y=value, colour=Species, linetype=gear)) + scale_y_continuous(trans="log10", name="Yield") + scale_x_continuous(name="Time")
if (nrow(object@params@species_params)>12){
p <- ggplot(ym) + geom_line(aes(x=time,y=value, group=Species)) + scale_y_continuous(trans="log10", name="Yield") + scale_x_continuous(name="Time")
}
if (print_it)
print(p)
return(p)
}
#---------------------------------------------------------------------------------------------------------------------
#' Plot the abundance spectra of each species and the background population
#'
#' After running a projection, the spectra of the abundance of each species and the background population can be plotted.
#' The abundance is averaged over the specified time range (a single value for the time range can be used to plot a single time step).
#' The abundance can be in terms of numbers or biomass, depending on the \code{biomass} argument.
plotSpectra <- function(object, time_range = max(as.numeric(dimnames(object@n)$time)), min_w =min(object@params@w)/100, biomass = TRUE, print_it = TRUE, ...){
time_elements <- get_time_elements(object,time_range)
spec_n <- apply(object@n[time_elements,,,drop=FALSE],c(2,3), mean)
background_n <- apply(object@n_pp[time_elements,,drop=FALSE],2,mean)
y_axis_name = "Abundance"
if (biomass){
spec_n <- sweep(spec_n,2,object@params@w,"*")
background_n <- background_n * object@params@w_full
y_axis_name = "Biomass"
}
# Make data.frame for plot
plot_dat <- data.frame(value = c(spec_n), Species = dimnames(spec_n)[[1]], w = rep(object@params@w, each=nrow(object@params@species_params)))
plot_dat <- rbind(plot_dat, data.frame(value = c(background_n), Species = "Background", w = object@params@w_full))
# lop off 0s in background and apply min_w
plot_dat <- plot_dat[(plot_dat$value > 0) & (plot_dat$w >= min_w),]
p <- ggplot(plot_dat) + geom_line(aes(x=w, y = value, colour = Species, linetype=Species)) + scale_x_continuous(name = "Size", trans="log10") + scale_y_continuous(name = y_axis_name, trans="log10")
if (nrow(object@params@species_params)>12){
p <- ggplot(plot_dat) + geom_line(aes(x=w, y = value, group = Species)) + scale_x_continuous(name = "Size", trans="log10") + scale_y_continuous(name = y_axis_name, trans="log10")
}
if (print_it)
print(p)
return(p)
}
#---------------------------------------------------------------------------------------------------------------------
#' Plot the feeding level of each species by size
#'
#' After running a projection, plot the feeding level of each species by size.
#' The feeding level is averaged over the specified time range (a single value for the time range can be used).
plotFeedingLevel <- function(object, time_range = max(as.numeric(dimnames(object@n)$time)), print_it = TRUE, ...){
feed_time <- getFeedingLevel(object=object, time_range=time_range, drop=FALSE, ...)
feed <- apply(feed_time, c(2,3), mean)
plot_dat <- data.frame(value = c(feed), Species = dimnames(feed)[[1]], w = rep(object@params@w, each=nrow(object@params@species_params)))
p <- ggplot(plot_dat) + geom_line(aes(x=w, y = value, colour = Species, linetype=Species)) + scale_x_continuous(name = "Size", trans="log10") + scale_y_continuous(name = "Feeding Level", lim=c(0,1))
if (nrow(object@params@species_params)>12){
p <- ggplot(plot_dat) + geom_line(aes(x=w, y = value, group = Species)) + scale_x_continuous(name = "Size", trans="log10") + scale_y_continuous(name = "Feeding Level", lim=c(0,1))
}
if (print_it)
print(p)
return(p)
}
#---------------------------------------------------------------------------------------------------------------------
#' Plot M2 of each species by size
#'
#' After running a projection, plot M2 of each species by size.
#' M2 is averaged over the specified time range (a single value for the time range can be used to plot a single time step).
plotM2 <- function(object, time_range = max(as.numeric(dimnames(object@n)$time)), print_it = TRUE, ...){
m2_time <- getM2(object, time_range=time_range, drop=FALSE, ...)
m2 <- apply(m2_time, c(2,3), mean)
plot_dat <- data.frame(value = c(m2), Species = dimnames(m2)[[1]], w = rep(object@params@w, each=nrow(object@params@species_params)))
p <- ggplot(plot_dat) + geom_line(aes(x=w, y = value, colour = Species, linetype=Species)) + scale_x_continuous(name = "Size", trans="log10") + scale_y_continuous(name = "M2", lim=c(0,max(plot_dat$value)))
if (nrow(object@params@species_params)>12){
p <- ggplot(plot_dat) + geom_line(aes(x=w, y = value, group = Species)) + scale_x_continuous(name = "Size", trans="log10") + scale_y_continuous(name = "M2", lim=c(0,max(plot_dat$value)))
}
if (print_it)
print(p)
return(p)
}
#---------------------------------------------------------------------------------------------------------------------
#' Plot total fishing mortality of each species by size
#'
#' After running a projection, plot the total fishing mortality of each species by size.
#' The total fishing mortality is averaged over the specified time range (a single value for the time range can be used to plot a single time step).
plotFMort <- function(object, time_range = max(as.numeric(dimnames(object@n)$time)), print_it = TRUE, ...){
f_time <- getFMort(object, time_range=time_range, drop=FALSE, ...)
f <- apply(f_time, c(2,3), mean)
plot_dat <- data.frame(value = c(f), Species = dimnames(f)[[1]], w = rep(object@params@w, each=nrow(object@params@species_params)))
p <- ggplot(plot_dat) + geom_line(aes(x=w, y = value, colour = Species, linetype=Species)) + scale_x_continuous(name = "Size", trans="log10") + scale_y_continuous(name = "Total fishing mortality", lim=c(0,max(plot_dat$value)))
if (nrow(object@params@species_params)>12){
p <- ggplot(plot_dat) + geom_line(aes(x=w, y = value, group = Species)) + scale_x_continuous(name = "Size", trans="log10") + scale_y_continuous(name = "Total fishing mortality", lim=c(0,max(plot_dat$value)))
}
if (print_it)
print(p)
return(p)
}
#---------------------------------------------------------------------------------------------------------------------
#' Summary plot for \code{MizerSim} objects
#'
#' After running a projection, produces 5 plots in the same window:
#' feeding level, abundance spectra, predation mortality and fishing
#' mortality of each species by size; and biomass of each species through
#' time.
#' This method just uses the other plotting methods and puts them
#' all in one window.
plotSummary <- function(x, ...){
p1 <- plotFeedingLevel(x,print_it = FALSE,...)
p2 <- plotSpectra(x,print_it = FALSE,...)
p3 <- plotBiomass(x,print_it = FALSE,...)
p4 <- plotM2(x,print_it = FALSE,...)
p5 <- plotFMort(x,print_it = FALSE,...)
grid.newpage()
glayout <- grid.layout(3,2) # widths and heights arguments
vp <- viewport(layout = glayout)
pushViewport(vp)
vplayout <- function(x,y)
viewport(layout.pos.row=x, layout.pos.col = y)
print(p1+ theme(legend.position="none"), vp = vplayout(1,1))
print(p3+ theme(legend.position="none"), vp = vplayout(1,2))
print(p4+ theme(legend.position="none"), vp = vplayout(2,1))
print(p5+ theme(legend.position="none"), vp = vplayout(2,2))
print(p2+ theme(legend.position="right", legend.key.size=unit(0.1,"cm")), vp = vplayout(3,1:2))
}
# physio plots --------------------------------------------------------------------------------------------------------
# plot biomass
plotDynamics <- function(object, time_range = c(min(as.numeric(dimnames(object@n)$time)),max(as.numeric(dimnames(object@n)$time))), phenotype = TRUE, species = NULL, SpIdx = NULL, print_it = T, returnData = F, save_it = F, nameSave = "Biomass.png", ylimit = c(1e-11,NA)){
cbPalette <- c("#999999","#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #9 colors for colorblind
# get the phenotype biomass through time (need at least 2 time steps for now)
biomass <- getBiomass(object)
time_elements <- get_time_elements(object,time_range)
biomass <- biomass[time_elements,]
# getting rid of the species that went extinct during the initialisation
if (is.null(SpIdx))
for (i in unique(object@params@species_params$species))
if (sum(biomass[, i]) != 0 & dim(object@params@species_params[object@params@species_params$species == i, ])[1] != 1)
SpIdx = c(SpIdx, i)
# sum the phenotype biomass per species
biomassSp = NULL
biomassTemp = biomass
colnames(biomassTemp) = object@params@species_params$species
for (i in SpIdx)
{
biomassPhen = biomassTemp[,which(colnames(biomassTemp) == i)]
if(!is.null(dim(biomassPhen))) biomassPhen = apply(biomassPhen,1,sum)
biomassSp = cbind(biomassSp,biomassPhen)
}
colnames(biomassSp) = SpIdx
# apply SpIdx on biomass as well
spSub <- object@params@species_params$ecotype[object@params@species_params$species %in% SpIdx]
biomass <- biomass[,as.numeric(dimnames(biomass)$species) %in% spSub]
plotBiom <- function(x)
{
Biom <- melt(x) # melt for ggplot
colnames(Biom) = c("time","phen","value")
# Due to log10, need to set a minimum value
min_value <- 1e-30
Biom <- Biom[Biom$value >= min_value,]
# create a species column
Biom$sp = sapply(Biom$phen, function(x) as.numeric(unlist(strsplit(as.character(x), "")))[1])
return(Biom)
}
if (phenotype) BiomPhen <- plotBiom(biomass)
BiomSp <- plotBiom(biomassSp)
# multiple possibilities: which species? with or without phenotypes?
if (!is.null(species)) BiomSp <- BiomSp[BiomSp$sp == species, ]
if (phenotype)
{
if (!is.null(species)) BiomPhen <- BiomPhen[BiomPhen$sp == species, ]
p <- ggplot(BiomSp) +
geom_line(aes(x = time, y = value, colour = as.factor(sp), group = sp), size = 1.2) +
geom_line(data = BiomPhen, aes(x = time, y = value, colour = as.factor(sp), group = phen), alpha = 0.2) +
scale_y_log10(name = "Biomass in g.m^-3", limits = ylimit, breaks = c(1 %o% 10^(-30:4))) +
scale_x_continuous(name = "Time in years") +
labs(color='Species') +
theme(panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"),
legend.key = element_rect(fill = "white"))+
scale_colour_manual(values=cbPalette)+ # colorblind
ggtitle("Community biomass")
} else {
p <- ggplot(BiomSp) +
geom_line(aes(x = time, y = value, colour = as.factor(sp), group = sp), size = 1.2) +
scale_y_log10(name = "Biomass in g.m^-3", limits = ylimit, breaks = c(1 %o% 10^(-30:4))) +
scale_x_continuous(name = "Time in years") +
labs(color='Species') +
theme(panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"),
legend.key = element_rect(fill = "white"))+
scale_colour_manual(values=cbPalette)+ # colorblind
ggtitle("Community biomass")
}
if(save_it) ggsave(plot = p, filename = nameSave)
if (returnData) return(BiomSp) else if(print_it) return(p)
}
plotDynamicsMulti <- function(folder){
cbPalette <- c("#999999","#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #9 colors for colorblind
#NO FISHERIES PART
path_to_sim = paste(folder,"/normal",sep="")
bigSim <- bunchLoad(folder = path_to_sim)
sim <- superStich(bigSim)
#top left corner biomass of 1 stochastic run without fisheries
plot_dat <- biom(bigSim[[1]])
p1 <- ggplot(plot_dat[[1]]) +
geom_line(aes(x = time, y = value, colour = as.factor(bloodline), group = sp), size = 1.2) +
geom_line(data = plot_dat[[2]], aes(x = time, y = value, colour = as.factor(bloodline), group = sp), alpha = 0.2) +
scale_y_log10(name = expression(paste("Biomass in g.m"^"-3")), limits = c(1e-7, NA), breaks = c(1 %o% 10^(-11:-1))) +
scale_x_continuous(name = NULL,labels = NULL) +
#scale_x_continuous(name = "Time in years") +
labs(color='Species') +
theme(legend.title=element_blank(),panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"), legend.position="none",
legend.justification=c(1,1),legend.key = element_rect(fill = "white"))+ #none remove legend
scale_colour_manual(values=cbPalette)+ # colorblind
ggtitle("a)")
# bottom left corner, biomass of averaged run without fisheries
plot_dat <- biom(sim,phenotype = F)
p2 <- ggplot(plot_dat[[1]]) +
geom_line(aes(x = time, y = value, colour = as.factor(bloodline), group = sp), size = 1.2) +
scale_y_log10(name = expression(paste("Biomass in g.m"^"-3")), limits = c(1e-05, NA), breaks = c(1 %o% 10^(-5:-1))) +
scale_x_continuous(name = "Time in years") +
labs(color='Species') +
theme(legend.title=element_blank(),panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"), legend.position="none",
legend.justification=c(1,1),legend.key = element_rect(fill = "white"))+ #none remove legend
scale_colour_manual(values=cbPalette)+ # colorblind
ggtitle("c)")
#FISHERIES PART
path_to_sim = paste(folder,"/fisheries",sep="")
bigSim <- bunchLoad(folder = path_to_sim)
# dirContent <- dir(path_to_sim)
# bigSim = list()
# for(i in 1:length(dirContent))
# {
# if (file.exists(paste(path_to_sim,"/",dirContent[i],"/run.Rdata",sep = "")))
# {
# sim <- get(load(paste(path_to_sim,"/",dirContent[i],"/run.Rdata",sep="")))
# } else {
# sim <- get(load(paste(path_to_sim,"/",dirContent[i],"/defaultRun.Rdata",sep="")))
# sim = superOpt(sim)
# }
# bigSim[[i]] = sim
# rm(sim)
# }
sim <- superStich(bigSim)
#top right corner biomass of 1 stochastic run with fisheries
plot_dat <- biom(bigSim[[1]])
p3 <- ggplot(plot_dat[[1]]) +
geom_line(aes(x = time, y = value, colour = as.factor(bloodline), group = sp), size = 1.2) +
geom_line(data = plot_dat[[2]], aes(x = time, y = value, colour = as.factor(bloodline), group = sp), alpha = 0.2) +
scale_y_log10(name = NULL, limits = c(1e-7, NA), labels = NULL, breaks = c(1 %o% 10^(-11:-1))) +
scale_x_continuous(name = NULL,labels = NULL) +
labs(color='Species') +
theme(legend.title=element_blank(),panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"), legend.position="none",
legend.justification=c(1,1),legend.key = element_rect(fill = "white"))+ #none remove legend
scale_colour_manual(values=cbPalette)+ # colorblind
ggtitle("b)")
# bottom left corner, biomass of averaged run without fisheries
plot_dat <- biom(sim,phenotype = F)
p4 <- ggplot(plot_dat[[1]]) +
geom_line(aes(x = time, y = value, colour = as.factor(bloodline), group = sp), size = 1.2) +
scale_y_log10(name = NULL, limits = c(1e-5, NA), labels = NULL, breaks = c(1 %o% 10^(-11:-1))) +
scale_x_continuous(name = "Time in years") +
labs(color='Species') +
theme(legend.title=element_blank(),panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"), legend.position="none",
legend.justification=c(1,1),legend.key = element_rect(fill = "white"))+ #none remove legend
scale_colour_manual(values=cbPalette)+ # colorblind
ggtitle("d)")
#multiplot
path_to_png = paste(folder,"/popDynamics.png",sep="")
png(filename=path_to_png,width = 20, height = 20, units = "cm",res = 600)
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow=2, ncol=2,
widths = unit(c(10,10), "cm"),
heights = unit(c(15,5), "cm"))))
print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p2, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
print(p3, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
print(p4, vp = viewport(layout.pos.row = 2, layout.pos.col = 2))
dev.off()
}
plotDynamicsLong <- function(folder, SpIdx = NULL, comments = T, window = NULL, what = c("normal","fisheries"), dt = 0.1, returnData = F, SD = F)
{
tic()
#plotList <- list() # to store the plots
plot_datList <- list() #to store the data
multiSimInit <- bunchLoad(folder = paste(folder,"/init",sep=""))
#for (i in 1:length(multiSimInit)) multiSimInit[[i]] <- superOpt(multiSimInit[[i]])
if(comments) cat("Init sims loaded\n")
for (column in what) # are we plotting normal or fisheries sims ?
{
if (column == "normal")
{
listPosition = 1
multiSim <- bunchLoad(folder = paste(folder,"/normal",sep=""))
#for (i in 1:length(multiSim)) multiSim[[i]] <- superOpt(multiSim[[i]])
title = c("(a) Without fisheries","(b)","(c)")
cat("Normal runs\n")
} else if (column == "fisheries")
{
listPosition = 2
multiSim <- bunchLoad(folder = paste(folder,"/fisheries",sep=""))
#for (i in 1:length(multiSim)) multiSim[[i]] <- superOpt(multiSim[[i]])
title = c("(d) With fisheries","(e)","(f)")
cat("Fishery runs\n")
} else stop("I don't know what to plot")
template = multiSimInit[[1]]
longSimList <- list()
timeMax = multiSimInit[[1]]@params@species_params$timeMax[1] + multiSim[[1]]@params@species_params$timeMax[1]
#prepare the data
for (x in 1:length(multiSimInit))
{
if(comments) cat(sprintf("Using run %i\n",x))
# get the right species params
SummaryParams = template@params # structure and basics params
SummaryParams@species_params = rbind(multiSimInit[[x]]@params@species_params,multiSim[[x]]@params@species_params) # get the sp ID from both sim
SummaryParams@species_params$timeMax = timeMax # update the timemax
a <- SummaryParams@species_params
a <- a[order(a$ecotype, a$extinct, decreasing=TRUE),] # weird 3 lines to get rid of duplicates and keep the ones with the extinction value
a <- a[!duplicated(a$ecotype),]
SummaryParams@species_params = a[order(a$pop,a$ecotype),]
#if (is.null(SpIdx)) SpIdx = sort(unique(SummaryParams@species_params$species))
if (comments) cat("Data handling\n")
result = list(list(multiSimInit[[x]],multiSim[[x]]),SummaryParams) # cannot use finalTOuch exactly as the data as been divided by 10 (dimnames issues)
gc()
sim = result[[1]] # get the dat
SummaryParams = result[[2]] # get the params
rm(result) # get space back
sim <- sim[lapply(sim, length) > 0] # if a sim is empty
template = sim[[length(sim)]] # to keep a template of mizer object somewhere
gc()
# stitiching the sims together
Dtime = SummaryParams@species_params$timeMax[1] * dt
Dsp = length(SummaryParams@species_params$ecotype)
Dw = dim(sim[[1]]@n)[3]
# put all the sim at the same dimension
biomList <- list()
for (i in 1:length(sim)) # for each sim
{
biom <- array(data = 0, dim = c(dim(sim[[i]]@n)[1], Dsp, Dw), dimnames = list(dimnames(sim[[i]]@n)$time, SummaryParams@species_params$ecotype, SummaryParams@w)) # create an array of the right dimension
names(dimnames(biom)) = c("time", "species", "size")
for (j in dimnames(sim[[i]]@n)$sp) # fill it when necessary
biom[, which(dimnames(biom)$species == j), ] = sim[[i]]@n[, which(dimnames(sim[[i]]@n)$sp == j), ]
biomList[[i]] <- biom[-1,,] # store it
}
biom <- do.call("abind", list(biomList, along = 1)) # abind the list
names(dimnames(biom)) = list("time", "species", "size")
dimnames(biom)$time = seq(1, SummaryParams@species_params$timeMax[1]*dt)[-c(length(seq(1, SummaryParams@species_params$timeMax[1]*dt))-1,length(seq(1, SummaryParams@species_params$timeMax[1]*dt)))] # system D
# I have to do the phyto aussi
phyto <- do.call(abind, c(lapply(sim, function(isim)
isim@n_pp), along = 1))
# taking care of the effort
effort <- do.call(rbind, lapply(sim, function(isim)
isim@effort))
names(dimnames(effort)) = list("time", "effort")
dimnames(effort)$time = seq(1, SummaryParams@species_params$timeMax[1]*dt)
# reconstruct the mizer object
sim = template
sim@params = SummaryParams
sim@n = biom
sim@effort = effort
sim@n_pp = phyto
rm(list = "biom", "phyto", "effort")
gc()
sim <- superOpt(sim)
longSimList[[x]] <- sim
}
if (comments) cat("Data ready\n")
# get the initial stuff
SpIdx = sort(unique(longSimList[[1]]@params@species_params$species)) # determine spidx if not already given by user
no_sp = length(SpIdx) # get the species number from this
if (comments) cat("Initialisation done\n")
for(i in 1:20) gc()
if(SD)
{
iSim <- NULL
for (simNumber in 1:length(longSimList)) iSim <- abind(iSim,as.matrix(plotDynamics(longSimList[[simNumber]], returnData = T, SpIdx = SpIdx)), along = 3)
meanSp <- apply(iSim[,"value",],1, mean)
sdSp <- apply(iSim[,"value",],1, sd)
plot_dat<- data.frame(iSim[,c(1,4),1],meanSp,sdSp)
plot_datList[[listPosition]] <- plot_dat
} else {
sim <- superStich(longSimList)
#rm(longSimList)
for(i in 1:20) gc()
if (comments) cat("Simulations concatened\n")
plot_dat <- plotDynamics(sim,returnData = T,phenotype = F, SpIdx = SpIdx)
#plot_dat <- biom(sim,phenotype = F)
if (comments) cat("Phenotypes reunification\n")
plot_datList[[listPosition]] <- plot_dat
}
}
if (comments) print(toc())
if(returnData) return(plot_datList)
p <- ggplot(plot_datList[[1]]) +
geom_line(aes(x = time, y = value, colour = as.factor(sp), group = sp)) +
scale_y_log10(name = expression(paste("Biomass in g.m"^"-3")), limits = window) +
scale_x_continuous(name = "Time in years") +
theme(legend.title=element_blank(),panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"),
legend.justification=c(1,1),legend.key = element_rect(fill = "white"))+
ggtitle(NULL)
return(p)
}
# plot size spectrum
plotSS <- function(object, time_range = max(as.numeric(dimnames(object@n)$time)), min_w =min(object@params@w)/100,
biomass = TRUE, print_it = TRUE, species = TRUE, save_it = FALSE,nameSave = "SizeSpectrum.png", returnData = FALSE, ...){
cbPalette <- c("#999999","#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #9 colors for colorblind
min_w = 0.001
time_elements <- get_time_elements(object,time_range)
spec_n <- apply(object@n[time_elements,,,drop=FALSE],c(2,3), mean)
background_n <- apply(object@n_pp[time_elements,,drop=FALSE],2,mean)
y_axis_name = "Abundance"
if (biomass){
spec_n <- sweep(spec_n,2,object@params@w,"*")
background_n <- background_n * object@params@w_full
y_axis_name = "Biomass"
}
# Make data.frame for plot
plot_datSP <- data.frame(value = c(spec_n), Species = dimnames(spec_n)[[1]], w = rep(object@params@w, each=nrow(object@params@species_params)), bloodline = object@params@species_params$species)
plot_datPkt <- data.frame(value = c(background_n), Species = "Background", w = object@params@w_full)
if (species)
{
dimnames(spec_n)$species = object@params@species_params$species
SpIdx = unique(object@params@species_params$species)
spec_sp = matrix(data = NA, ncol = dim(spec_n)[2], nrow = length(SpIdx), dimnames = list(as.character(SpIdx),dimnames(spec_n)$size))
names(dimnames(spec_sp))=list("species","size")
for (i in 1:dim(spec_sp)[1])
{
temp = spec_n # save to manip
temp[which(rownames(spec_n) != i), ] = 0 # make everything but the targeted species to go 0 to have correct normalisation
temp = apply(temp, 2, sum)
spec_sp[i, ] = temp
}
plot_datSP <- data.frame(value = c(spec_sp), Species = dimnames(spec_sp)[[1]], w = rep(object@params@w, each=length(SpIdx)))
}
# lop off 0s in background and apply min_w
plot_datSP <- plot_datSP[(plot_datSP$value > 0) & (plot_datSP$w >= min_w),]
plot_datPkt <- plot_datPkt[(plot_datPkt$value > 0) & (plot_datPkt$w >= min_w),]
#getPalette = colorRampPalette(brewer.pal(9, "Set1"))# increase the number of colors used
if (species)
{
p <- ggplot(plot_datSP) +
geom_line(aes(x=w, y = value, colour = as.factor(Species), group = Species)) +
geom_line(data = plot_datPkt, aes(x = w, y = value, linetype = Species), size = 1.5) +
scale_x_log10(name = "Size in g", breaks = c(1 %o% 10^(-6:5)))+
scale_y_log10(name = "Abundance density in individuals.m^-3") + #, limits = c(1e-6,1e4)) +
theme(panel.background = element_blank(),legend.key = element_rect(fill = "white"))+
theme_bw()+
#scale_colour_manual(values=cbPalette, name = "Species")+ # colorblind
#scale_color_grey(name = "Species")+ # grey
ggtitle("Size spectrum")
}
else
{
p <- ggplot(plot_datSP) +
geom_line(aes(x=w, y = value, colour = as.factor(bloodline), group = Species)) +
geom_line(data = plot_datPkt, aes(x = w, y = value, colour = Species), size = 1.5) +
scale_x_log10(name = "Size in g", breaks = c(1 %o% 10^(-6:5)))+
scale_y_log10(name = "Abundance density in individuals.m^-3", limits = c(1e-35,1e4)) +
theme(panel.background = element_blank(),legend.key = element_rect(fill = "white"))+
theme_bw()+
scale_colour_manual(values=cbPalette)+ # colorblind
#scale_color_grey(name = "Species")+ # grey
ggtitle("Size spectrum")
}
if(save_it) ggsave(plot = p, filename = nameSave)
if (returnData) return(plot_datSp) else if(print_it) return(p)
}
# fisheries mortality
plotFM <- function(object, time_range = max(as.numeric(dimnames(object@n)$time)), print_it = T, returnData = F, ...){
cbPalette <- c("#999999","#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #9 colors for colorblind
f_time <- getFMort(object, time_range=time_range, drop=FALSE, ...)
f <- apply(f_time, c(2,3), mean)
plot_dat <- data.frame(value = c(f), Species = dimnames(f)[[1]], w = rep(object@params@w, each=nrow(object@params@species_params)))
# take the first digit of the species column and put it in a new column
plot_dat$bloodline = sapply(plot_dat$Species, function(x) as.numeric(unlist(strsplit(as.character(x), "")))[1])
p <- ggplot(plot_dat) +
geom_line(aes(x=w, y = value, group = bloodline,color = as.factor(bloodline))) +
scale_x_continuous(name = "Size", trans="log10", breaks = c(1 %o% 10^(-1:5)), limits = c(1e-2,1e5)) +
scale_y_continuous(name = "Total fishing mortality", lim=c(0,max(plot_dat$value))) +
theme(legend.title=element_text(),panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"), legend.position="none",
legend.justification=c(1,1),legend.key = element_rect(fill = "white"))+ #none remove legend
scale_colour_manual(values=cbPalette)+ # colorblind
ggtitle(NULL)
if (returnData) return(plot_dat) else if (print_it) return(p)
}
# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols: Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
# plot feeding / satiation level
plotFood <- function(object, time_range = max(as.numeric(dimnames(object@n)$time)), species = T, throughTime = F, start = 1000, every = 1000, print_it = T, returnData = F, save_it =F, nameSave = "Feeding.png"){
cbPalette <- c("#999999","#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #9 colors for colorblind
if (throughTime)
{
time_range = seq(start,max(as.numeric(dimnames(object@n)$time)),every)
time_range = c(time_range,max(as.numeric(dimnames(object@n)$time))) # so it counts the last time step which is probably not even
time_range = unique(time_range)
feeding = array(data = NA, dim = c(length(unique(object@params@species_params$species)),100,length(time_range)),
dimnames = list(as.character(unique(object@params@species_params$species)),object@params@w,time_range))
Critfeeding = matrix(data=NA, nrow = length(time_range), ncol= 100, dimnames = list(time_range,object@params@w))
for (i in time_range)
{
feed_time <- getFeedingLevel(object=object, time_range=i, drop=FALSE)#, ...) # get the feeding time
feed <- apply(feed_time, c(2,3), mean) # average on the time frame
Cfeed_time <- getCFeedingLevel(object=object, time_range=i, drop=FALSE)#, ...) # get the critical feeding level
Critfeed <- apply(Cfeed_time, c(2,3), mean) # average on the time frame
Critfeed <- Critfeed[1,] # all rows the same
dimnames(feed)$sp = object@params@species_params$species
SpIdx = unique(object@params@species_params$species) # get the species names
feed_sp = matrix(data = NA, ncol = dim(feed)[2], nrow = length(SpIdx), dimnames = list(SpIdx,dimnames(feed)$w)) # prepare the new object
names(dimnames(feed_sp))=list("species","size")
for (j in SpIdx)
{
temp = feed # save to manip
temp[which(rownames(feed) != j), ] = 0 # keep the ecotypes from the species only
temp = apply(temp, 2, sum)
temp = temp / length(which(rownames(feed)==j)) # do the mean (in 2 steps)
feed_sp[which(rownames(feed_sp)==j), ] = temp
}
feeding[,,which(dimnames(feeding)[[3]] == i)] = feed_sp
Critfeeding[which(dimnames(Critfeeding)[[1]] == i),] = Critfeed
}
a <- c(object@params@species_params$w_inf[1:9]) # to get vline of different col, need to create a data frame
vlines <- data.frame(xint = a,grp = c(1:9))
plot_dat = melt(feeding)
colnames(plot_dat) = c("species","size","time","value")
plot_crit = melt(Critfeeding)
colnames(plot_crit) = c("time","size","value")
p <- ggplot(plot_dat) +
geom_line(aes(x=size, y = value, colour = as.factor(species))) +
geom_line(data = plot_crit, aes(x = size, y = value), linetype = "dashed") +
scale_x_log10(name = "Size") +
scale_y_continuous(name = "Feeding Level", lim=c(0,1))+
geom_vline(data = vlines,aes(xintercept = xint,colour = as.factor(grp)), linetype = "dashed") +
facet_grid(time ~ .)+
scale_colour_manual(values=cbPalette, name = "Species")+ # colorblind
theme(panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"))+
ggtitle("Feeding level through time")
if(save_it) ggsave(plot = p, filename = nameSave)
if (returnData) return(list(plot_dat,plot_crit)) else if(print_it) return(p)
}
feed_time <- getFeedingLevel(object=object, time_range=time_range, drop=FALSE) #, ...) # get the feeding time
feed <- apply(feed_time, c(2,3), mean) # average on the time frame
Cfeed_time <- getCFeedingLevel(object=object, time_range=time_range, drop=FALSE)#, ...) # get the critical feeding level
Critfeed <- apply(Cfeed_time, c(2,3), mean) # average on the time frame
Critfeed <- Critfeed[1,] # all rows the same
if (species) # if I want to display species instead of ecotypes
{
dimnames(feed)$sp = object@params@species_params$species
SpIdx = sort(unique(object@params@species_params$species)) # get the species names
feed_sp = matrix(data = NA, ncol = dim(feed)[2], nrow = length(SpIdx), dimnames = list(SpIdx,dimnames(feed)$w)) # prepare the new object
names(dimnames(feed_sp))=list("species","size")
for (i in SpIdx)
{
temp = feed # save to manip
temp[which(rownames(feed) != i), ] = 0 # keep the ecotypes from the species only
temp = apply(temp, 2, sum)
temp = temp / length(which(rownames(feed)==i)) # do the mean (in 2 steps)
feed_sp[which(rownames(feed_sp)==i), ] = temp
}
feed = feed_sp
}
a <- c(object@params@species_params$w_inf[1:9]) # to get vline of different col, need to create a data frame
vlines <- data.frame(xint = a,grp = c(1:9))
plot_dat <- data.frame(value = c(feed), species = dimnames(feed)[[1]], size = rep(object@params@w, each=length(dimnames(feed)[[1]])))
name = paste("Feeding level at time",time_range,sep=" ")
p <- ggplot(plot_dat) +
geom_line(aes(x=size, y = value, colour = as.factor(species))) +
geom_hline(yintercept = Critfeed[1], linetype = "dashed", color = "red") +
geom_vline(data = vlines,aes(xintercept = xint,colour = as.factor(grp)), linetype = "dashed") +
scale_x_log10(name = "Size", breaks = c(1 %o% 10^(-3:5))) +
scale_y_continuous(name = "Feeding Level", lim=c(0,1))+
scale_colour_manual(values=cbPalette, name = "Species")+ # colorblind
theme(panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"),
legend.key = element_rect(fill = "white"))+
ggtitle(name)
if(save_it) ggsave(plot = p, filename = nameSave)
if (returnData) return(list(plot_dat,Critfeed)) else if(print_it) return(p)
}
# plot of the number of ecotype per time step
PlotNoSp <- function(object, print_it = T, returnData = F, init = T, dt = 0.1, save_it = F, nameSave = "NoSp.png"){
if (is.list(object)) # this means that it gets a list of sim and needs to do the average
{
avgList = list()
for (x in 1:length(object))
{
sim = object[[x]]
# I really need to fix the time max in the sims ;(;(;(
if(!init) {
TimeMax = sim@params@species_params$timeMax[1] + 40000
timeStart = 40000} else {
TimeMax = sim@params@species_params$timeMax[1]
timeStart = 1
}
SumPar = cbind(sim@params@species_params$pop,sim@params@species_params$extinct)
colnames(SumPar) = c("Apparition","Extinction")
rownames(SumPar) = sim@params@species_params$ecotype
SumPar = SumPar[order(SumPar[,1],decreasing=FALSE),]
SumPar = as.data.frame(SumPar) # little dataframe with species apparition and extinction
for (i in 1:dim(SumPar)[1]) if (SumPar$Extinction[i] == 0) SumPar$Extinction[i] = TimeMax # the not extinct ones get the end sim as extinction value
avg = matrix(data = 0, nrow = TimeMax, ncol =4)
avg[,1] = seq(1:TimeMax)*0.1
ApCount = length(which(SumPar$Apparition == 0)) # number of starting species
ExCount = 0
SumParEx = SumPar[order(SumPar$Extinction,decreasing=F),] #need this order for extinction in loop
for (i in timeStart:TimeMax) # for each time step
{
for (j in 1:dim(SumPar)[1])
if (SumPar$Apparition[j] <= i & SumPar$Extinction[j] >= i) # how many phenotypes are alive right now?
avg[i,2] = avg[i,2] + 1
if (i %in% SumPar$Apparition) ApCount = ApCount + 1 # how many in total
avg[i,3] = ApCount
if (i %in% SumParEx$Extinction) ExCount = ExCount + 1 #how many extinct?
avg[i,4] = ExCount
}
avg = as.data.frame(avg)
dimnames(avg)[[2]] = list("time", "number","apparition","extinction") # dataframe of the number of species at each time step
avg = avg[seq(1,dim(avg)[1],10),]
avgList[[x]] = avg
}
# here I have a list of the demographic data of each sim
# now I need to do stats on them
#DemoMean = do.call(mean, )
#ans1 = aaply(laply(avgList, as.matrix), c(2, 3), mean)
avgMatrix <- abind(avgList, along=3) # convert the list in an array
avgMean = apply(avgMatrix, c(1,2), mean) # do the stat manip
avgSd = apply(avgMatrix, c(1,2), sd)
# I have to check if the sd function works properly, but not right now
# f = apply((sweep(yo1,2,avgMean,"-"))^2,2,sum)/length(avgList) # this is the variance at each time step
# g = sqrt(f) # this is the standard population deviation at each time step
# yo1 = avgList[[1]]
# yo2 = avgList[[2]]
stat = data.frame(avgMean,avgSd[,-1])# prepare my data
colnames(stat) = c("time","Mno","Mpop","Mext","Sno","Spop","Sext")
# first build the standard deviation curve only
g1 <- ggplot(stat)+
geom_smooth(aes(x = time, y = (Mno-Sno))) +
geom_smooth(aes(x=time, y = (Mno+Sno))) +
geom_smooth(aes(x=time, y = (Mext-Sext)))+
geom_smooth(aes(x=time, y = (Mext+Sext)))
gg1 <- ggplot_build(g1)
dfRibbon <- data.frame(xNo = gg1$data[[1]]$x, yminNo = gg1$data[[1]]$y, ymaxNo = gg1$data[[2]]$y, #and extract the smooth data for the ribbon
xExt = gg1$data[[3]]$x, yminExt = gg1$data[[3]]$y, ymaxExt = gg1$data[[4]]$y)
p <- ggplot(stat) +
stat_smooth(aes(x = time, y = Mno, color = "green")) +
#geom_smooth(aes(x = time, y = (Mno-Sno))) +
#geom_smooth(aes(x=time, y = (Mno+Sno)))+
geom_ribbon(data = dfRibbon, aes(x = xNo, ymin = yminNo, ymax = ymaxNo),
fill = "grey", alpha = 0.4)+
geom_smooth(aes(x=time, y = Mext, color = "blue"))+
#geom_smooth(aes(x=time, y = (Mext-Sext)))+
#geom_smooth(aes(x=time, y = (Mext+Sext)))+
geom_ribbon(data = dfRibbon, aes(x = xExt, ymin = yminExt, ymax = ymaxExt),
fill = "grey", alpha = 0.4)+
# geom_smooth(data = yo1 ,aes(x=time, y = number))+
# geom_smooth(data = yo2 ,aes(x=time, y = number))+
scale_x_continuous(name = "Time (yr)") +
scale_y_continuous(name = "Number of phenotypes")+
scale_colour_discrete(labels = c("Extinct","Alive"))+
theme(legend.title=element_blank(),
legend.position=c(0.19,0.95),
legend.justification=c(1,1),
legend.key = element_rect(fill = "white"),
panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"))+
guides(color=guide_legend(override.aes=list(fill=NA)))+
ggtitle("Variation of phenotype's number throughout the simulation")
if(save_it) ggsave(plot = p, filename = nameSave)
if (returnData) return(list(stat,dfRibbon)) else if (print_it)return(p)
}
# I really need to fix the time max in the sims ;(;(;(
if(!init) {
TimeMax = object@params@species_params$timeMax[1] + 40000
timeStart = 40000} else {
TimeMax = object@params@species_params$timeMax[1]
timeStart = 1
}
SumPar = cbind(object@params@species_params$pop,object@params@species_params$extinct) # weird things happen without the as.numeric
colnames(SumPar) = c("Apparition","Extinction")
rownames(SumPar) = object@params@species_params$ecotype
SumPar = SumPar[order(SumPar[,1],decreasing=FALSE),]
SumPar = as.data.frame(SumPar) # little dataframe with species apparition and extinction
for (i in 1:dim(SumPar)[1]) if (SumPar$Extinction[i] == 0) SumPar$Extinction[i] = TimeMax # the not extinct ones get the end sim as extinction value
avg = matrix(data = 0, nrow = TimeMax, ncol =4)
avg[,1] = seq(1:(TimeMax))
ApCount = length(which(SumPar$Apparition < timeStart)) # number of starting species
ExCount = length(which(SumPar$Extinction < timeStart))
SumParEx = SumPar[order(SumPar$Extinction,decreasing=F),] #need this order for extinction in loop
for (i in (timeStart):(TimeMax)) # for each time step
{
for (j in 1:dim(SumPar)[1])
if (SumPar$Apparition[j] <= i & SumPar$Extinction[j] >= i) # how many phenotypes are alive right now?
avg[i,2] = avg[i,2] + 1
if (i %in% SumPar$Apparition) ApCount = ApCount + 1 # how many in total
avg[i,3] = ApCount
if (i %in% SumParEx$Extinction) ExCount = ExCount + 1 #how many extinct?
avg[i,4] = ExCount
}
avg = as.data.frame(avg)
dimnames(avg)[[2]] = list("time", "number","apparition","extinction") # dataframe of the number of species at each time step
p <- ggplot(avg) +
geom_line(aes(x = time, y = number, color = "green")) +
#geom_line(aes(x=time, y = apparition, color = "blue"))+
geom_line(aes(x=time, y = extinction, color = "red"))+
scale_x_continuous(name = "Time (yr)") +
scale_y_continuous(name = "Number of phenotypes")+
#scale_colour_discrete(labels = c("Total","Alive","Extinct"))+
scale_colour_discrete(labels = c("Alive","Extinct"))+
theme(legend.title=element_blank(),
legend.position=c(0.19,0.95),
legend.justification=c(1,1),
legend.key = element_rect(fill = "white"),
panel.background = element_rect(fill = "white", color = "black"),
panel.grid.minor = element_line(colour = "grey92"))+
guides(color=guide_legend(override.aes=list(fill=NA)))+
ggtitle("Variation of phenotype's number throughout the simulation")
if(save_it) ggsave(plot = p, filename = nameSave)
if (returnData) return(list(stat,dfRibbon)) else if (print_it) return(p)
}
# my plot of the dead (x 3 because that's why)
#' Plot M2 of each species by size
plotUdead <- function(object, time_range = max(as.numeric(dimnames(object@n)$time)),species = T, throughTime = F, print_it = TRUE, returnData = F, ...){
cbPalette <- c("#999999","#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #9 colors for colorblind
a <- c(object@params@species_params$w_inf[1:9]) # to get vline of different col, need to create a data frame
vlines <- data.frame(xint = a,grp = c(1:9))
if (throughTime)
{
time_range = seq(500,max(as.numeric(dimnames(object@n)$time)),500)
time_range = c(time_range,max(as.numeric(dimnames(object@n)$time))) # so it counts the last time step which is probably not even
time_range = unique(time_range)
mortality = matrix(data = NA, nrow = length(time_range), ncol = 100, dimnames = list(time_range,object@params@w))
for (i in time_range)
{
m2_time <- getM2(object, time_range=i, drop=FALSE, ...)
m2 <- apply(m2_time, c(2,3), mean)
mortality[which(rownames(mortality)==i),] <- m2[1,] #all rows are the same
}
plot_dat = melt(mortality)
colnames(plot_dat) = list("time","size","value")