-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStratPlot.R
1341 lines (1246 loc) · 51 KB
/
StratPlot.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
## Super easy plotting of paleodata in R
## Ilja Kocken
## Student of Marine Sciences at Utrecht University
## First version: 2014-04-11
## Latest version: 2017-03-07
## Plot your age/depth data beautifully, with options for logaritmic axes, easy
## polygon- and bar plots plus options to add Geologic Time Scale information.
## necessary libraries for certain functions
library(astrochron) # for tuning stratigraphic series
library(png) # for working with png images
library(jpeg) # for working with jpg images
library(rasterImage) # for transposing images, might not work w/ Windows!
library(raster) # for working with raster images
StratPlot <- function(var, ...){
## S3-method for the main plotting function
## Args:
## var: the variable to plot: a dataframe, vector, matrix or list
## ...: other arguments
UseMethod("StratPlot", var)
}
StratPlot.default <- function(age, var, age.dir = "h", GTS = F,
pol = F, pol0 = NULL, pol.col = "#4682B4E6",
border = NA, bar = F, bar.col = "orange",
bar.lwd = 2, add = F, error = NULL,
error.type = "bars", error.col = "#BEBEBEE6",
error.lwd = 1, error.code = 3, gap.size = NULL,
abc = NULL, abc.adj = NULL, exaggerate = NULL,
ex.type = "l", ex.lty = 1, ex.col = "gray",
mar = "inherit",
xax = if (age.dir == "h") 1 else 3, yax = 2,
xlim = NULL, ylim = NULL, xlab = NULL,
ylab = NULL, xlab.line = 2, ylab.line = 2,
xlab.font = 1, ylab.font = 1, xlab.adj = NA,
ylab.adj = NA, xlab.align = c(0.5, NA),
ylab.align = c(0.5, NA),
xlab.ang = NULL, ylab.ang = NULL, xax.labs = NULL,
yax.labs = NULL, xlab.cex = 1, ylab.cex = 1,
xtck = NULL, ytck = NULL, xntck = 2, yntck = 2,
las = 1, log = "", bty = "n", type = "o", lty = 1,
pch = 16, verbose = TRUE, ...) {
## Creates a plot based on a depth/age vector and a variable vector
## Args:
## age: vector with age or depth information
## var:
## age.dir: direction of age "v", "ver", "vertical" or "h" "hor" "horizontal"
## GTS colour scale on age axis
## value of exaggeration line to add
## polygon to plot
## bar to plot
## mar: or "auto" or specified
## logical, add to plot or start new one
## vector of relative errors or matrix/df of absolute values to plot
## don't draw lines when agediff is larger
## add index letter topleft
## positions of minor tick marks
## number of minor tick marks between major marks
## default plot/log options
## default positions of axes (1:4)
## other graphical parameters
## age:
## var:
## age.dir = "h"
## GTS = F:
## pol = F:
## pol0 = NULL:
## pol.col = "#4682B4E6",
## border = NA:
## bar = F:
## bar.col = "orange",
## bar.lwd = 2:
## add = F:
## error = NULL:
## error.type = "bars":
## error.col = "#BEBEBEE6":
## error.lwd = 1:
## error.code = 3:
## gap.size = NULL:
## abc = NULL:
## abc.adj = NULL:
## exaggerate = NULL:
## ex.type = "l":
## ex.lty = 1:
## ex.col = "gray":
## mar = "inherit":
## xax = if (age.dir == "h") 1 else 3:
## yax = 2:
## xlim = NULL:
## ylim = NULL:
## xlab = NULL:
## ylab = NULL:
## xlab.line = 2:
## ylab.line = 2:
## xlab.font = 1:
## ylab.font = 1:
## xlab.adj = NA:
## ylab.adj = NA:
## xlab.align = c(0.5, NA):
## ylab.align = c(0.5, NA):
## xlab.ang = NULL:
## ylab.ang = NULL:
## xax.labs = NULL:
## yax.labs = NULL:
## xlab.cex = 1:
## ylab.cex = 1:
## xtck = NULL:
## ytck = NULL:
## xntck = 2:
## yntck = 2:
## las = 1:
## log = "":
## bty = "n":
## type = "o":
## lty = 1:
## pch = 16:
## verbose = TRUE:
## ...:
## Era = F, Period = T, Epoch = T, Age = F, GTSfrac = .05,
## TODO: add standard Geologic Time Scale to region near x or y axis
## xlab.pos = NULL, ylab.pos = NULL,
## check var and age
if (length(var) != length(age)) {
stop("Unequal length of var and age")
}
## insert gaps where needed
if (!is.null(gap.size)) {
too.large <- which(diff(age) > gap.size)
df <- InsertEmpty(data.frame(age, var), too.large)
age <- df$age
var <- df$var
}
## check age.dir
if (!age.dir %in% c("v", "ver", "vertical", "h", "hor", "horizontal")) {
stop("age.dir must be either 'v', 'ver', 'vertical' or 'h', 'hor, 'horizontal'")
} else {
age.dir <- substr(age.dir, 1, 1) # age.dir is converted to either 'v' or 'h'
}
if (!add) {
## mar (depends on xax and yax, which are not checked)
if (identical(mar, "auto")) {
mar <- c(if (1 %in% xax || 1 %in% yax) 5 else 2,
if (2 %in% xax || 2 %in% yax) 5 else 2,
if (3 %in% xax || 3 %in% yax) 5 else 2,
if (4 %in% xax || 4 %in% yax) 5 else 2) + .1
} else if (identical(mar, "inherit")) {
mar <- par(no.readonly = TRUE)$mar
}
## xlim, ylim
if (age.dir == "h") {
if (is.null(xlim)) xlim <- range(age, na.rm = TRUE)
if (is.null(ylim)) ylim <- range(var, na.rm = TRUE)
} else {
if (is.null(xlim)) xlim <- range(var, na.rm = TRUE)
if (is.null(ylim)) ylim <- rev(range(age, na.rm = TRUE))
}
## default xlab, ylab
if (age.dir == "h") {
if (is.null(xlab)) {
if (max(age, na.rm = T) < 100) {
if (verbose) message("Assuming age is given in Ma")
xlab <- "Age (Ma)"
} else {
if (verbose) message("Assuming age is given in ka")
xlab <- "Age (ka)"
}
}
if (is.null(ylab)) {
if (verbose) message("No ylab provided")
ylab <- ""
}
} else {
if (is.null(xlab)) {
if (verbose) message("No xlab provided")
xlab <- ""
}
if (is.null(ylab)) {
if (max(age, na.rm = T) < 100) {
if (verbose) message("Assuming age is given in Ma")
ylab <- "Age (Ma)"
} else {
if (verbose) message("Assuming age is given in ka")
ylab <- "Age (ka)"
}
}
}
## set up plotting margins
par(mar = mar, bty = bty)
## set up empty plot
plot(1, type = "n", xlim = xlim, ylim = ylim, log = log,
xlab = "", ylab = "", axes = FALSE, ...)
## axes added later
}
if (pol || bar) {
## baseline to draw polygon and bar to
if (is.null(pol0)) {
## logarithmic var axis -> draw polygon to minimum value
if ((age.dir == "h" && grepl("y", log)) ||
(age.dir == "v" && grepl("x", log))) {
pol0 <- min(var)
} else {
pol0 <- 0
}
}
}
## plot polygon
if (pol) {
if (anyNA(var) || anyNA(age)) {
if (verbose) message("NAs found in var/age, currently ignoring")
nona <- data.frame(var = var, age = age)
nona <- nona[complete.cases(nona), ]
x <- c(nona$age[1], nona$age, tail(nona$age, n = 1))
y <- c(pol0, nona$var, pol0)
## TODO: create polygons per non-NA region, like we do with errorregion
## enc <- rle(!is.na(var))
## endIdxs <- cumsum(enc$lengths)
## for (i in 1:length(enc$lengths)) {
## if (enc$values[i]) {
## endIdx <- endIdxs[i]
## startIdx <- endIdx - enc$lengths[i] + 1
## subvar <- var[startIdx:endIdx]
## subage <- age[startIdx:endIdx]
## x <- c(left, subvar, left)
## y <- c(subage[1], age, tail(age, n = 1))
## }
## }
} else {
## not sure if I want to use the current left or use:
## min(var, na.rm = TRUE) - .04 * diff(range(var, na.rm = TRUE))
x <- c(age[1], age, tail(age, n = 1))
y <- c(pol0, var, pol0)
}
polygon(x = if (age.dir == "h") x else y, y = if (age.dir == "h") y else x,
col = pol.col, border = border)
}
## plot exaggeration
if (!is.null(exaggerate)) {
points(if (age.dir == "h") age else var * exaggerate,
if (age.dir == "h") var * exaggerate else age,
type = ex.type, lty = ex.lty, col = ex.col)
}
## plot error bars/area
if (!is.null(error)) {
## if (length(error) > 0) { # plot errorstuff
if (!all(error.type %in% c("bars", "area"))) {
stop(paste0("Incorrect error.type '",
error.type,
"', specify error.type as 'bars' or 'area'"))
}
if ("bars" %in% error.type) {
ErrorBarsPlot(age, var, error, col = error.col, code = error.code,
age.dir = age.dir, lwd = error.lwd)
}
if ("area" %in% error.type) {
ErrorAreaPlot(age, var, error, col = error.col,
age.dir = age.dir)
}
## }
}
## plot bars (added after errors to overlap the possible areas)
if (bar) {
if (is.null(pol0)) pol0 <- 0
segments(x0 = if (age.dir == "h") age else rep(pol0, length(var)),
y0 = if (age.dir == "h") rep(pol0, length(var)) else age,
x1 = if (age.dir == "h") age else var,
y1 = if (age.dir == "h") var else age,
col = bar.col, lwd = bar.lwd)
}
## plot the actual record
points(x = if (age.dir == "h") age else var,
y = if (age.dir == "h") var else age, type = type,
pch = pch, lty = lty, ...)
## add axes
if (!add) {
## loop so that I can specify both 1 and 2 for example.
for (i in xax) {
AddAxis(i, lim = xlim, ntck = xntck, las = las, labels = xax.labs)
AddAxLab(xlab, i, line = xlab.line, adj = xlab.adj, font = xlab.font,
ang = xlab.ang, lab.adj = xlab.align, cex = xlab.cex)
}
for (i in yax) {
AddAxis(i, lim = ylim, ntck = yntck, las = las, labels = yax.labs)
AddAxLab(ylab, i, line = ylab.line, adj = ylab.adj, font = ylab.font,
ang = ylab.ang, lab.adj = ylab.align, cex = ylab.cex)
}
if (GTS) {
AddGTS(age.dir = age.dir, Era = F, Period = T, Epoch = T, Age = F, frac = GTSfrac)
}
}
## add corner ABC
if (!is.null(abc)) {
if (is.null(abc.adj)) {
abc.adj <- 0.04 * abs(diff(par("usr")[1:2]))
}
AddABC(abc, abc.adj)
}
}
ErrorBarsPlot <- function(age, var = NULL, error, col = "#BEBEBEE6", code = 3,
lwd = 1, length = 0.05, angle = 90, age.dir = "h") {
## add error bars to a plot
## Args:
## age: a vector of age/depth values
## var: a vector of the variable of interest
## error: a vector/matrix/dataframe of error values
## col: the colour of the error bars
## code: the code of the 'arrows' argument, 3 is caps
## lwd: the line width of the error bars
## length: the length of the whiskers of the error bars
## angle: the angle of the arrows to be drawn, default 90 degrees
## age.dir: the direction that age is plotted in, "h" or "v"
## data frame or matrix with two columns
if (is.data.frame(error) || is.matrix(error) && ncol(error) == 2) {
## Error handling
if (!(nrow(error) == 1 || nrow(error) == length(var)))
warning("Number of rows in error not equal to var length, recycling")
if (age.dir == "h")
arrows(age, error[, 1], age, error[, 2], col = col, length = length,
angle = angle, code = code, lwd = lwd)
else if (age.dir == "v")
arrows(error[, 1], age, error[, 2], age, col = col, length = length,
angle = angle, code = code, lwd = lwd)
} else { # single (vector of) error value(s)
if (!(length(error) == length(var) || length(error) == 1))
warning("Length of error not equal to var length, recycling")
if (age.dir == "h") {
arrows(x0 = age, y0 = var - error, x1 = age, y1 = var + error,
col = col, length = length, angle = angle, code = code,
lwd = lwd)
}
else if (age.dir == "v") {
arrows(x0 = var - error, y0 = age, x1 = var + error, y1 = age,
col = col, length = length, angle = angle, code = code,
lwd = lwd)
}
}
}
ErrorAreaPlot <- function(age, var = NULL, error, col = "#BEBEBE4D",
age.dir = "h", ...) {
## add an error area to a plot
## Args:
## age: a vector of age/depth values
## var: a vector of the variable of interest
## error: a vector/matrix/dataframe of error values
## col: the colour of the error bars
## age.dir: the direction that age is plotted in, "h" or "v"
## ...: other arguments for the polygon function
## Error handling
if (!is.numeric(error) && is.null(var))
stop("Provide either dataframe/matrix of low and high error values or vector of relative error values.")
## error is a dataframe/matrix with 2 columns for negative and positive
## absolute error values
if (is.data.frame(error) || is.matrix(error) && ncol(error) == 2) {
## TODO: support for NA values in age when specifying strict errorvalues
if (nrow(error) != length(var))
warning("Number of rows in error not equal to var length, recycling")
x <- c(age, rev(age))
y <- c(error[, 1], rev(error[, 2]))
} else {
if (anyNA(var) | anyNA(age)) {
enc <- rle(!is.na(var)) # calculate amount of non-NA polygons
endIdxs <- cumsum(enc$lengths) # lengths of polygons
for (i in seq_along(enc$lengths)){ # for each polygon
if (enc$values[i]){ # for non-na regions
endIdx <- endIdxs[i]
startIdx <- endIdx - enc$lengths[i] + 1
subdat <- var[startIdx:endIdx]
subsd <- error[startIdx:endIdx]
subage <- age[startIdx:endIdx]
x <- c(subdat - subsd, rev(subdat + subsd))
y <- c(subage, rev(subage))
}
}
} else {
x <- c(age, rev(age))
y <- c(var - error, rev(var + error))
}
}
polygon(x = if (age.dir == "h") x else y, y = if (age.dir == "h") y else x,
col = col, border = NA, ...)
}
StratPlot.data.frame <- function(var, # dataframe
age = NULL, # optional vector
age.dir = "h", # "v", "ver", "vertical" or "h" "hor" "horizontal"
pol = F, bar = F, # polygon/bar
gap.size = NULL, # lines not drawn for timesteps > gap.size
oneplot = F, # logical, if TRUE plot all variables in the same plot
genframe = T, # show plots in same window
add = F, error = NULL, # vector of errors to plot (note: relative values!)
stacked = F, # logical, calculate cumulative sum for vars, currently doesn't work.
..., xax = if (age.dir == "h") 1 else 3, # default position of x-axis
log = "",
yax = 2, # default position of yaxis
las = 1, # default direction of axis labels
mar = "auto", # generated based on xax and yax
ylab = NULL, xlab = NULL, xlim = NULL,
ylim = NULL,
xntck = 2, yntck = 2,
bty = "n", col = "black",
lwd = 1, lty = 1, type = "o", pch = 16,
error.type = "bars", pol0 = NULL,
error.col = "#BEBEBEE6", pol.col = "#4682BEE6",
ex.col = "#325C87", bar.col = "#325C87",
border = NULL, legend = NULL) {
## Takes a dataframe of one or multiple variable(s) to create a (set of) plot(s)
## subset numeric columns
## var <- var[, sapply(var, is.numeric)]
## TODO: do this as option?
## check var and age
if (!is.null(age)){
if (length(age) != nrow(var)) {
stop("Length of age is unequal to nrow(var)")
}
## TODO add gapmaker support!
if (verbose) message("Assuming only variables in dataframe")
} else { # only var is provided
## find column that has age/depth
depth.col <- grep("depth", names(var), ignore.case = TRUE)
if (length(depth.col) > 1) warning("multiple depth columns found, using first")
age.col <- grep("age|time", names(var), ignore.case = TRUE)
if (length(age.col) > 1) warning("multiple age columns found, using first")
## depth.col found but age.col isn't
if (length(depth.col) >= 1 && length(age.col) == 0) {
## extract age/depth from var
age <- var[, depth.col[1]]
var <- var[, -depth.col[1]]
## overwrite agelab if default
if (age.dir == "h") {
if (is.null(xlab)) {
xlab <- "Depth (mbsf)"
}
} else if (age.dir == "v") {
if (is.null(ylab)) {
ylab <- "Depth (mbsf)"
}
}
## age.col found but depth.col isn't
} else if (length(depth.col) == 0 && length(age.col) >= 1) {
## extract age/depth from var
age <- var[, age.col[1]]
var <- var[, -age.col[1]]
## both age.col and depth.col found, using age.col
} else if (length(depth.col) > 0 && length(age.col) > 0) {
## TODO: interactive selection of desired age
## extract age/depth from var
age <- var[, age.col[1]] # for now we just use age if both are available
## omit depth and age
var <- var[, - c(depth.col[1], age.col[1])]
} else { # no depth.col, no age.col found: use first column
## extract age/depth from var
age <- var[, 1]
var <- var[, -1]
if (verbose) message("Assuming age or depth in first column of var")
}
}
## number of variables after extraction of age
if (is.vector(var)) {
nvar <- 1
} else {
nvar <- ncol(var)
}
## parsing of x- and ylab
if (age.dir == "h") {
if (!is.null(ylab)) {
## TODO: parse ylab in similar manner as xlab, with proper expression check
if (is.character(ylab) && length(ylab) > 1 && length(ylab) != nvar){
stop("Incorrect length of ylab")
}
if (class(ylab) == "formula"){
if (length(ylab == 1)) {
ylab <- as.expression(ylab)
} else {
lapply(ylab, as.expression)
}
}
} else {
if (verbose) message("Using varnames as ylabs")
ylab <- names(var)
}
if (length(ylab) > 1 && length(ylab) == nvar) {
ylabs <- ylab
}
} else { # age.dir = v
if (!is.null(xlab)) {
if (length(xlab) > 1 && length(xlab) != nvar){
stop("Incorrect length of xlab")
}
if (class(xlab) == "formula"){
if (length(xlab == 1)) {
xlab <- as.expression(xlab)
} else {
xlabs <- lapply(xlab, as.expression)
}
}
} else {
if (verbose) message("Using varnames as xlabs")
xlabs <- names(var)
}
if (length(xlab) > 1 && length(xlab) == nvar) {
xlabs <- xlab
}
}
## specific plotting variables can also be defined for all variables in var
if (length(type) > 1) {
if (length(type) == nvar) {
types <- type
} else stop("Incorrect length of type")
}
if (length(pch) > 1) {
if (length(pch) == nvar) {
pchs <- pch
} else stop("Incorrect length of pch")
}
if (length(col) > 1) {
if (length(col) == nvar) {
cols <- col
} else stop("Incorrect length of col")
} else cols <- NULL
if (length(lty) > 1) {
if (length(lty) == nvar) {
ltys <- lty
} else stop("Incorrect length of lty")
}
if (length(lwd) > 1) {
if (length(lwd) == nvar) {
lwds <- lwd
} else stop("Incorrect length of lwd")
}
if (length(pol) > 1) {
if (length(pol) == nvar) {
pols <- pol
} else stop("Incorrect length of pol")
}
if (length(pol.col) > 1) {
if (length(pol.col) == nvar) {
pol.cols <- pol.col
} else stop("Incorrect length of pol.col")
}
if (length(bar) > 1) {
if (length(bar) == nvar) {
bars <- bar
} else stop("Incorrect length of bar")
}
if (length(bar.col) > 1) {
if (length(bar.col) == nvar) {
bar.cols <- bar.col
} else stop("Incorrect length of bar.col")
}
if (length(ex.col) > 1) {
if (length(ex.col) == nvar) {
ex.cols <- ex.col
} else stop("Incorrect length of ex.col")
}
if (is.list(ylim)){
if (length(ylim) == nvar) {
ylims <- ylim
} else stop("Incorrect length of ylim")
}
## TODO: also do this for bty?, error.type, error.col, pol0 and border?
if (length(log) > 1) {
if (length(log) == nvar) {
logs <- log
} else stop("Incorrect length of log")
}
## set up the plotting region
## last is to check if it wasn't a df with only 2 columns
if (!oneplot && genframe && is.data.frame(var)) {
if (age.dir == "h") {
par(mfrow = c(nvar, 1))
} else {
par(mfrow = c(1, nvar))
}
}
## call StratPlot.numeric, multiple times if necessary
for (i in seq_len(nvar)) {
StratPlot(if (nvar == 1) {
var
} else if (stacked) {
if (i == 1) var[, 1]
else rowSums(var[, 1:i])
} else { var[, i] }, age = age, age.dir = age.dir,
gap.size = gap.size,
pol = if (exists("pols")) pols[i] else pol, ## pol = pol[i],
bar = if (exists("bars")) bars[i] else bar,
add = if (is.null(add)) { if ((oneplot || stacked) && i != 1) TRUE else FALSE } else { add },
error = error, xax = xax, yax = yax, mar = mar, ## TODO: change exists check for something else b/c it currently uses the global space
ylab = if (exists("ylabs")) ylabs[i] else ylab,
xlab = if (exists("xlabs")) xlabs[i] else xlab, xntck = xntck,
yntck = yntck,
xlim = if (oneplot && age == "v") range(var, na.rm = TRUE) else xlim,
ylim = if (oneplot && age == "h") range(var, na.rm = TRUE) else if (exists("ylims")) ylims[[i]] else ylim,
bty = bty, lty = if (exists("ltys")) ltys[i] else lty,
col = if (!is.null(cols)) cols[i] else col,
lwd = if (exists("lwds")) lwds[i] else lwd,
type = if (exists("types")) types[i] else type,
pch = if (exists("pchs")) pchs[i] else pch,
log = if (exists("logs")) logs[i] else log,
error.type = error.type, error.col = error.col, pol0 = pol0,
pol.col = if (exists("pol.cols")) pol.cols[i] else pol.col,
bar.col = if (exists("bar.cols")) bar.cols[i] else bar.col,
ex.col = if (exists("ex.cols")) ex.cols[i] else ex.col,
border = border, ...)
}
if (!is.null(legend)) {
legend("topright", legend = legend, col = if (exists("cols")) cols else col,
lty = if (exists("ltys")) ltys else lty,
lwd = if (exists("lwds")) lwds else lwd,
pch = if (exists("pchs")) pchs else pch)
}
}
StratPlot.list <- function(ls, ...) {
## apply the stratplotter to all the elements of a list
## Args:
## ls: the list who's elements are to be plotted
## ...: other arguments
lapply(ls, StratPlot, ...)
}
SubsetRange <- function(dat, min, max, column = "depth") {
## subset dataframe to range of age/depth
## Args:
## dat: the dataframe to be subsetted
## min: the minimum value to subset by
## max: the maxiumum value to subset by
## column: the column name to subset by
return(dat[dat[, column] > min & dat[, column] < max, ])
}
GapMaker <- function(df, gap.size = .5, column = "age") {
## insert empty rows between values that differ more than gap.size
## Args:
## df: the data frame
## gap.size: the size of the gaps
## column: the column name to base gaps on
too.large <- which(diff(df[, column]) > gap.size)
df <- InsertEmpty(df, too.large)
return(df)
}
InsertEmpty <- function(df, afterrow) {
## insert empty rows in a dataframe after afterrow
## Args:
## df: the dataframe
## afterrow: empty row is inserted after this row
## create indices for the data order
df$id <- seq_len(nrow(df))
df[max(df$id) + seq_along(afterrow), ] <- NA
df$id[is.na(df$id)] <- afterrow + .5
df <- df[order(df$id), ]
df <- df[ , !names(df) %in% "id"]
return(df)
}
AddAxis <- function(ax = 1, labels = NULL, lim = NULL, ntck = NULL,
tck = NULL, las = 1, ...) {
## adds a pretty axis, with minor ticks and pretty log options
## Args:
## ax:
## labels:
## lim:
## ntck:
## tck:
## las:
## ...:
if (is.null(ntck)) {
ntck <- 2
}
if (ax %in% c(1, 3)) { # bottom or top x-axis
log <- par("xlog")
if (is.null(lim) && log) {
lim <- c(1e-100, 1e100) # just use a mega range...
}
} else if (ax %in% c(2, 4)) { # left or right y-axis
log <- par("ylog")
if (is.null(lim) && log) {
lim <- c(1e-100, 1e100)
}
} else stop("ax must be 1: bottom, 2: left, 3: top or 4: right")
## if the axis is on a logarithmic scale
if (log) {
## the log10 range of powers that need something done
pow <- c(
if (lim[1] == 0) -100
else if (lim[1] > 0) floor(log10(lim[1]))
else - floor(log10(-lim[1])),
if (lim[2] == 0) -100
else if (lim[2] > 0) ceiling(log10(lim[2]))
else -ceiling(log10(-lim[2])))
if (is.null(tck))
tck <- c(1:10 %o% 10^((pow)[1]:(pow)[2]))
## log axis with nicer 10^pow labels for all the ax
if (is.null(labels))
labels <- sapply((pow)[1]:(pow)[2], # or -xpow[1]?
function(i) {
as.expression(bquote(10^ .(i)))})
axis(ax, at = 10^(pow[1]:pow[2]), labels = labels, las = las, ...)
} else { # non-log axis
## default axis
axis(ax, las = las, labels = labels, ...)
## find stepsize used in default axis
if (is.null(tck))
stepsize <- abs(diff(axTicks(ax)[1:2])) / ntck
## add ntck ticks between
tck <- seq(from = min(axTicks(ax)) - stepsize * ntck,
to = max(axTicks(ax)) + stepsize * ntck,
by = stepsize)
}
## minor x-axis tick marks
axis(ax, at = tck, labels = FALSE, tcl = -.2)
}
## if (grepl("x", log) || las == 1) 3
## else 2
AddAxLab <- function (lab = "", side = 1, line = 2, adj = NA,
lab.adj = c(0.5, NA), cex = 1, ang = NULL, pos = NULL,
font = 1, x = NULL, y = NULL, ...) {
## add axis labels
## Args:
## lab:
## side:
## line:
## adj:
## lab.adj:
## cex:
## ang:
## pos:
## font:
## x:
## y:
## ...:
## no angle, and no specific x and y position for the label just use mtext
if (is.null(ang) || (!is.null(x) && !is.null(y))) {
mtext(lab, side = side, line = line, adj = adj, pos = pos,
font = font, cex = cex, ...)
} else {
if (side %in% c(1, 3)) { # default horizontal axis:
## parse x from adj
if (is.null(x)) {
if (is.na(adj)) {
x <- mean(par("usr")[1:2])
} else {
x <- par("usr")[1] + diff(par("usr")[1:2]) * adj
}
}
## parse y from line
if (is.null(y)) {
if (side == 1) {
y <- par("usr")[3] - diff(par("usr")[3:4])/28 * line
} else if (side == 3) {
y <- par("usr")[4] + diff(par("usr")[3:4])/28 * line
}
}
} else if (side %in% c(2, 4)) { # vertical axis
## parse y from adj
if (is.null(y)) {
if (is.na(adj)) {
y <- mean(par("usr")[3:4])
} else {
y <- par("usr")[3] + diff(par("usr")[3:4]) * adj
}
}
## parse x from line
if (is.null(x)) {
if (side == 2) {
x <- par("usr")[1] - diff(par("usr")[1:2])/28 * line/2
} else if (side == 4) {
x <- par("usr")[2] + diff(par("usr")[1:2])/28 * line/2
}
}
}
text(x, y, labels = lab, font = font, srt = ang, pos = pos, xpd = TRUE,
adj = lab.adj, cex = cex, ...)
}
}
AddABC <- function(char = "A", xadj = 0.04 * abs(diff(par("usr")[1:2])),
yadj = 0.04 * abs(diff(par("usr")[3:4])), cex = 2) {
## add large a/b/c in top left corner of current plot
## TODO: also work for log axes
xpos <- par("usr")[1] + xadj
ypos <- par("usr")[4] + yadj
mtext(char, 3, at = xpos, cex = cex)
## text(xpos, ypos, char, cex = cex, xpd = NA)
}
AddGTS <- function(age, xleft = NULL, xright = NULL, frac = 0.05,
agelim = range(age), age.dir = "h",
type = NULL,
Eon = T, Era = T, Period = T, Epoch = T, Age = T,
Chron = T,
horizontal.text = NULL, relwidth = NULL, cex.text = NULL,
verbose = T) {
## Add Geologic Time Scale information to a plot
## check types
if (is.null(type)) {
type <- c(Eon, Era, Period, Epoch, Age, Chron)
}
## subset types to plot
alltypes = c("Eon", "Era", "Period", "Epoch", "Age", "Chron")
types <- alltypes[type]
if (verbose) cat("\nplotting types:", types)
## read GTS table with color and age info
## todo: make this sharable
if (sum(types %in% alltypes[1:5]) > 0) {
GTS <- read.csv("~/Dropbox/StratPlot/GTS_colours.csv", stringsAsFactors = F)
GTS$hex <- rgb(GTS$R, GTS$G, GTS$B, maxColorValue = 255)
GTS$mean <- (GTS$end - GTS$start) / 2 + GTS$start
## order the type factor
GTS$type <- factor(GTS$type, alltypes[1:5], ordered = T)
}
## read chron table
if (sum(types %in% alltypes[6]) > 0) {
Chron <- read.csv("~/Dropbox/StratPlot/Chronages.csv", stringsAsFactors = F)
Chron$name <- Chron$Pol
Chron$hex <- "#000000"
Chron$hex[grepl("r", Chron$Pol)] <- "#FFFFFF"
Chron$start <- c(22, Chron$GTS2012[-nrow(Chron)])
Chron$end <- Chron$GTS2012
Chron$mean <- (Chron$end - Chron$start) / 2 + Chron$start
}
## default xleft/xright
if (is.null(xleft)) {
if (age.dir == "h") {
xleft <- par("usr")[3]
} else {
xleft <- par("usr")[1]
}
}
if (verbose) cat(" from ", xleft)
if (is.null(xright)) {
if (age.dir == "h") {
fullright <- par("usr")[4]
} else {
fullright <- par("usr")[2]
}
xright <- xleft + frac * (diff(c(xleft, fullright)))
}
if (verbose) cat(" to ", xright, "\n")
if (is.null(relwidth)) {
## default relwidths
relwidth <- c(0.08, 0.08, 0.1, 0.3, 0.44, 0.44)
## subset/make relative to selected types
relwidth <- relwidth[type] / sum(relwidth[type])
}
if (is.null(horizontal.text)) {
if (age.dir == "h") horizontal.text <- c(F, F, F, F, F, F)[type]
else horizontal.text <- c(F, F, F, T, T, T)[type]
}
if (is.null(cex.text)) {
cex.text <- c(1, 1, 1, .8, .7, 0.7)[type]
}
## this subfunction plots one gts bar
PlotGTS <- function(xleft, xright, gts, ad, td = T, cex.t, textpos = NULL) {
## add rectangles with appropriate colour
rect(if (ad == "h") gts$start else xleft,
if (ad == "h") xleft else gts$start,
if (ad == "h") gts$end else xright,
if (ad == "h") xright else gts$end,
col = gts$hex, border = Darken(gts$hex))
## add name in centre
## TODO: if the centre is outside of the plot margins, add it to
## the closest plot area
## TODO: xright if Chron
text(if (ad == "h") gts$mean else mean(c(xleft, xright)),
if (ad == "h") mean(c(xleft, xright)) else gts$mean,
labels = gts$name,
srt = if (td) 0 else 90,
cex = cex.t, pos = textpos)
}
nbars <- sum(type)
totwidth <- diff(c(xleft, xright))
## loop over type, so one loop is one bar of age info
for (bar in seq_len(nbars)) {
xright <- xleft + relwidth[bar] * totwidth
PlotGTS(xleft, xright,
if (types[bar] != "Chron") GTS[GTS$type == types[bar], ]
else Chron,
ad = age.dir, td = horizontal.text[bar], cex.t = cex.text[bar],
textpos = if (types[bar] != "Chron") NULL else NULL)
## TODO: fix text position for chron to right of xright with pos = 4.
xleft <- xright
}
}
## TODO: create addChron function that does the same as AddGTS but with
## normal/reversed magnetostrat + names
Darken <- function(color = col, factor=1.4){
## darken a colour
## Args:
## color: the colour input
## factor: the factor by which to darken
## Returns: the darkened colour
col <- col2rgb(color)
col <- col/factor
col <- rgb(t(col), maxColorValue=255)
col
}
Lighten <- function(color = col, factor=1.4){
## lighten a colour
## Args:
## color: the colour input
## factor: the factor by which to lighten
## Returns: the lightened colour
col <- col2rgb(color)
col <- col*factor
col <- rgb(t(as.matrix(apply(col, 1, function(x) if (x > 255) 255 else x))), maxColorValue=255)
col
}
## adds a linear model with confidence levels to the plot
plotLM <- function(x = NULL, y = NULL, confidence = 0.90,
col = "red", lty = 2, lwd = 1) {
## linmod = NULL,
## if (is.null(linmod) && (is.null(x) && is.null(y))) stop("Specify x and y or linmod")
## if (is.null(linmod)) linmod <- lm(y ~ x)
linmod <- lm(y ~ x)
## TODO: doesn't work with only linmod because of variable names in newdata
## plot(a,y,xlim=c(20,90),ylim=c(0,80))
abline(linmod, col="red")
newx <- seq(par("usr")[1], par("usr")[2], length.out = 100)
prd<-predict(linmod,
newdata = data.frame(x = newx),
interval = c("confidence"),
level = confidence, type="response")
lines(newx,prd[,2],col = col, lty = lty, lwd = lwd)
lines(newx,prd[,3],col = col, lty = lty, lwd = lwd)
}
## plots the R2 value of a linear model in a corner
plotLMinfo <- function(linmod, pos = "topleft", formula.offset = 1, digits = 4) {
r2 <- bquote(R^2~"="~.(format(summary(linmod)$adj.r.squared,
digits = digits)))
form <- bquote("y ="~.(format(summary(linmod)$coefficients[2],
digits = digits))~
"x +"~.(format(summary(linmod)$coefficients[1],
digits = digits)))
lgdinfo <- legend(pos, bty="n", legend = form, trace = T)
legend(lgdinfo$rect$left, lgdinfo$rect$top + formula.offset,
bty="n", legend = r2, trace = T)
}