-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
plot.R
1445 lines (1299 loc) · 51.7 KB
/
plot.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
#
# xts: eXtensible time-series
#
# Copyright (C) 2009-2015 Jeffrey A. Ryan jeff.a.ryan @ gmail.com
#
# Contributions from Ross Bennett and Joshua M. Ulrich
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
current.xts_chob <- function() invisible(get(".xts_chob",.plotxtsEnv))
# Currently not necessary, but potentially very useful:
# http://www.fromthebottomoftheheap.net/2011/07/23/passing-non-graphical-parameters-to-graphical-functions-using/
chart.lines <- function(x,
type="l",
lty=1,
lwd=2,
lend=1,
col=NULL,
up.col=NULL,
dn.col=NULL,
legend.loc=NULL,
...){
xx <- current.xts_chob()
switch(type,
h={
# use up.col and dn.col if specified
if (!is.null(up.col) && !is.null(dn.col)){
colors <- ifelse(x[,1] < 0, dn.col, up.col)
} else {
colors <- if (is.null(col)) 1 else col
}
if (length(colors) < nrow(x[,1]))
colors <- colors[1]
# x-coordinates for this column
xcoords <- xx$get_xcoords(x[,1])
lines(xcoords,x[,1],lwd=2,col=colors,lend=lend,lty=1,type="h",...)
},
p=, l=, b=, c=, o=, s=, S=, n={
if(is.null(col))
col <- xx$Env$theme$col
if(length(lty) < NCOL(x)) lty <- rep(lty, length.out = NCOL(x))
if(length(lwd) < NCOL(x)) lwd <- rep(lwd, length.out = NCOL(x))
if(length(col) < NCOL(x)) col <- rep(col, length.out = NCOL(x))
for(i in NCOL(x):1) {
# x-coordinates for this column
xcoords <- xx$get_xcoords(x[,i])
lines(xcoords, x[,i], type=type, lend=lend, col=col[i],
lty=lty[i], lwd=lwd[i], ...)
}
},
{
# default case
warning(paste(type, "not recognized. Type must be one of
'p', 'l', 'b, 'c', 'o', 'h', 's', 'S', 'n'.
plot.xts supports the same types as plot.default,
see ?plot for valid arguments for type"))
}
)
if(!is.null(legend.loc)){
lc <- legend.coords(legend.loc, xx$Env$xlim, range(x, na.rm=TRUE))
legend(x=lc$x, y=lc$y, legend=colnames(x), xjust=lc$xjust, yjust=lc$yjust,
fill=col[1:NCOL(x)], bty="n")
}
}
add.par.from.dots <- function(call., ...) {
stopifnot(is.call(call.))
# from graphics:::.Pars
parnames <- c("xlog","ylog","adj","ann","ask","bg","bty","cex","cex.axis",
"cex.lab","cex.main","cex.sub","cin","col","col.axis","col.lab",
"col.main","col.sub","cra","crt","csi","cxy","din","err",
"family", "fg","fig","fin","font","font.axis","font.lab",
"font.main","font.sub","lab","las","lend","lheight","ljoin",
"lmitre","lty","lwd","mai","mar","mex","mfcol","mfg","mfrow",
"mgp","mkh","new","oma","omd","omi","page","pch","pin","plt",
"ps","pty","smo","srt","tck","tcl","usr","xaxp","xaxs","xaxt",
"xpd","yaxp","yaxs","yaxt","ylbias")
dots <- list(...)
argnames <- names(dots)
pm <- match(argnames, parnames, nomatch = 0L)
call.list <- as.list(call.)
# only pass the args from dots ('...') that are in parnames
as.call(c(call.list, dots[pm > 0L]))
}
chart.lines.expression <- function(...) {
mc <- match.call()
mc[[1]] <- quote(chart.lines)
as.expression(mc)
}
isNullOrFalse <- function(x) {
is.null(x) || identical(x, FALSE)
}
# Main plot.xts method.
# author: Ross Bennett (adapted from Jeffrey Ryan's chart_Series)
plot.xts <- function(x,
y=NULL,
...,
subset="",
panels=NULL,
multi.panel=FALSE,
col=1:8,
up.col=NULL,
dn.col=NULL,
bg="#FFFFFF",
type="l",
lty=1,
lwd=2,
lend=1,
main=deparse(substitute(x)),
observation.based=FALSE,
ylim=NULL,
yaxis.same=TRUE,
yaxis.left=TRUE,
yaxis.right=TRUE,
major.ticks="auto",
minor.ticks=NULL,
grid.ticks.on="auto",
grid.ticks.lwd=1,
grid.ticks.lty=1,
grid.col="darkgray",
labels.col="#333333",
format.labels=TRUE,
grid2="#F5F5F5",
legend.loc=NULL,
extend.xaxis=FALSE){
# Small multiples with multiple pages behavior occurs when multi.panel is
# an integer. (i.e. multi.panel=2 means to iterate over the data in a step
# size of 2 and plot 2 panels on each page
# Make recursive calls and return
if(is.numeric(multi.panel)){
multi.panel <- min(NCOL(x), multi.panel)
idx <- seq.int(1L, NCOL(x), 1L)
chunks <- split(idx, ceiling(seq_along(idx)/multi.panel))
# allow color and line attributes for each panel in a multi.panel plot
if(length(lty) < ncol(x)) lty <- rep(lty, length.out = ncol(x))
if(length(lwd) < ncol(x)) lwd <- rep(lwd, length.out = ncol(x))
if(length(col) < ncol(x)) col <- rep(col, length.out = ncol(x))
if(!is.null(panels) && nchar(panels) > 0){
# we will plot the panels, but not plot the data by column
multi.panel <- FALSE
} else {
# we will plot the data by column, but not the panels
multi.panel <- TRUE
panels <- NULL
# set the ylim based on the data passed into the x argument
if(yaxis.same)
ylim <- range(x[subset], na.rm=TRUE)
}
for(i in 1:length(chunks)){
tmp <- chunks[[i]]
p <- plot.xts(x=x[,tmp],
y=y,
...=...,
subset=subset,
panels=panels,
multi.panel=multi.panel,
col=col[tmp],
up.col=up.col,
dn.col=dn.col,
bg=bg,
type=type,
lty=lty[tmp],
lwd=lwd[tmp],
lend=lend,
main=main,
observation.based=observation.based,
ylim=ylim,
yaxis.same=yaxis.same,
yaxis.left=yaxis.left,
yaxis.right=yaxis.right,
major.ticks=major.ticks,
minor.ticks=minor.ticks,
grid.ticks.on=grid.ticks.on,
grid.ticks.lwd=grid.ticks.lwd,
grid.ticks.lty=grid.ticks.lty,
grid.col=grid.col,
labels.col=labels.col,
format.labels=format.labels,
grid2=grid2,
legend.loc=legend.loc,
extend.xaxis=extend.xaxis)
if(i < length(chunks))
print(p)
}
# NOTE: return here so we don't draw another chart
return(p)
}
cs <- new.replot_xts()
# major.ticks shouldn't be null so we'll set major.ticks here if it is null
if(is.null(major.ticks)) {
xs <- x[subset]
mt <- c(years=nyears(xs),
months=nmonths(xs),
days=ndays(xs))
major.ticks <- names(mt)[rev(which(mt < 30))[1]]
}
# add theme and charting parameters to Env
plot.call <- match.call(expand.dots=TRUE)
if(isTRUE(multi.panel)){
if(NCOL(x) == 1)
cs$set_asp(3)
else
cs$set_asp(NCOL(x))
} else {
cs$set_asp(3)
}
cs$Env$cex <- if (hasArg("cex")) eval.parent(plot.call$cex) else 0.6
cs$Env$mar <- if (hasArg("mar")) eval.parent(plot.call$mar) else c(3,2,0,2)
cs$Env$theme$up.col <- up.col
cs$Env$theme$dn.col <- dn.col
# check for colorset or col argument
# if col has a length of 1, replicate to NCOL(x) so we can keep it simple
# and color each line by its index in col
if(hasArg("colorset")) col <- eval.parent(plot.call$colorset)
if(length(col) < ncol(x)) col <- rep(col, length.out = ncol(x))
cs$Env$theme$col <- col
cs$Env$theme$rylab <- yaxis.right
cs$Env$theme$lylab <- yaxis.left
cs$Env$theme$bg <- bg
cs$Env$theme$grid <- grid.col
cs$Env$theme$grid2 <- grid2
cs$Env$theme$labels <- labels.col
cs$Env$theme$srt <- if (hasArg("srt")) eval.parent(plot.call$srt) else 0
cs$Env$theme$las <- if (hasArg("las")) eval.parent(plot.call$las) else 0
cs$Env$theme$cex.axis <- if (hasArg("cex.axis")) eval.parent(plot.call$cex.axis) else 0.9
cs$Env$format.labels <- format.labels
cs$Env$major.ticks <- if (isTRUE(major.ticks)) "auto" else major.ticks
cs$Env$minor.ticks <- if (isTRUE(minor.ticks)) "auto" else minor.ticks
cs$Env$grid.ticks.on <- if (isTRUE(grid.ticks.on)) "auto" else grid.ticks.on
cs$Env$grid.ticks.lwd <- grid.ticks.lwd
cs$Env$grid.ticks.lty <- grid.ticks.lty
cs$Env$type <- type
# if lty or lwd has a length of 1, replicate to NCOL(x) so we can keep it
# simple and draw each line with attributes by index
if(length(lty) < ncol(x)) lty <- rep(lty, length.out = ncol(x))
if(length(lwd) < ncol(x)) lwd <- rep(lwd, length.out = ncol(x))
cs$Env$lty <- lty
cs$Env$lwd <- lwd
cs$Env$lend <- lend
cs$Env$legend.loc <- legend.loc
cs$Env$extend.xaxis <- extend.xaxis
cs$Env$call_list <- list()
cs$Env$call_list[[1]] <- plot.call
cs$Env$observation.based <- observation.based
# Do some checks on x
if(is.character(x))
stop("'x' must be a time-series object")
# Raw returns data passed into function
cs$Env$xdata <- x
cs$Env$xsubset <- subset
cs$Env$column_names <- colnames(x)
cs$Env$nobs <- NROW(cs$Env$xdata)
cs$Env$main <- main
cs$Env$ylab <- if (hasArg("ylab")) eval.parent(plot.call$ylab) else ""
# guard against constant yrange by (if necessary) perturbing values
.perturbConstant <- function(yrange) {
if(isTRUE(all.equal(yrange[1L], yrange[2L]))) {
if(yrange[1L] == 0) {
yrange <- yrange + c(-1, 1)
} else {
yrange <- c(0.8, 1.2) * yrange[1L]
}
}
return(yrange)
}
# chart_Series uses fixed=FALSE and add_* uses fixed=TRUE, not sure why or
# which is best.
if(is.null(ylim)){
if(isTRUE(multi.panel)){
if(yaxis.same){
# set the ylim for the first panel based on all the data
yrange <- range(cs$Env$xdata[subset], na.rm=TRUE)
} else {
# set the ylim for the first panel based on the first column
yrange <- range(cs$Env$xdata[,1][subset], na.rm=TRUE)
}
} else {
# set the ylim based on all the data if this is not a multi.panel plot
yrange <- range(cs$Env$xdata[subset], na.rm=TRUE)
}
cs$set_ylim(list(structure(.perturbConstant(yrange), fixed=FALSE)))
cs$Env$constant_ylim <- range(cs$Env$xdata[subset], na.rm=TRUE)
} else {
# use the ylim arg passed in
cs$set_ylim(list(structure(ylim, fixed=TRUE)))
cs$Env$constant_ylim <- ylim
}
cs$set_frame(1,FALSE)
# compute the x-axis ticks for the grid
if(!isNullOrFalse(grid.ticks.on)) {
cs$add(expression(xcoords <- get_xcoords(),
x_index <- get_xcoords(at_posix = TRUE),
atbt <- axTicksByTime(.xts(,x_index)[xsubset], ticks.on=grid.ticks.on),
segments(xcoords[atbt],
get_ylim()[[2]][1],
xcoords[atbt],
get_ylim()[[2]][2],
col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty)),
clip=FALSE, expr=TRUE)
}
# Add frame for the chart "header" to display the name and start/end dates
cs$add_frame(0,ylim=c(0,1),asp=0.5)
cs$set_frame(1)
# add observation level ticks on x-axis if < 400 obs.
cs$add(expression(if(NROW(xdata[xsubset])<400)
{axis(1,at=get_xcoords(),labels=FALSE,col=theme$grid2,col.axis=theme$grid2,tcl=0.3)}),expr=TRUE)
# major x-axis ticks and labels
if(!isNullOrFalse(major.ticks)) {
cs$add(expression(xcoords <- get_xcoords(),
x_index <- get_xcoords(at_posix = TRUE),
axt <- axTicksByTime(.xts(,x_index)[xsubset], ticks.on=major.ticks, format.labels=format.labels),
axis(1,
at=xcoords[axt],
labels=names(axt),
las=theme$las, lwd.ticks=1.5, mgp=c(3,1.5,0),
tcl=-0.4, cex.axis=theme$cex.axis,
col=theme$labels, col.axis=theme$labels)),
expr=TRUE)
}
# minor x-axis ticks
if(!isNullOrFalse(minor.ticks)) {
cs$add(expression(xcoords <- get_xcoords(),
x_index <- get_xcoords(at_posix = TRUE),
axt <- axTicksByTime(.xts(,x_index)[xsubset], ticks.on=minor.ticks, format.labels=format.labels),
axis(1,
at=xcoords[axt],
labels=FALSE,
las=theme$las, lwd.ticks=0.75, mgp=c(3,1.5,0),
tcl=-0.4, cex.axis=theme$cex.axis,
col=theme$labels, col.axis=theme$labels)),
expr=TRUE)
}
# add main title and date range of data
text.exp <- c(expression(text(xlim[1],0.5,main,font=2,col=theme$labels,offset=0,cex=1.1,pos=4)),
expression(text(xlim[2],0.5,
paste(start(xdata[xsubset]),end(xdata[xsubset]),sep=" / "),
col=theme$labels,adj=c(0,0),pos=2)))
cs$add(text.exp, env=cs$Env, expr=TRUE)
cs$set_frame(2)
# add y-axis grid lines and labels
exp <- expression(segments(xlim[1],
y_grid_lines(get_ylim()[[2]]),
xlim[2],
y_grid_lines(get_ylim()[[2]]),
col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty))
if(yaxis.left){
exp <- c(exp,
# left y-axis labels
expression(text(xlim[1], y_grid_lines(get_ylim()[[2]]),
noquote(format(y_grid_lines(get_ylim()[[2]]), justify="right")),
col=theme$labels, srt=theme$srt, offset=1, pos=2,
cex=theme$cex.axis, xpd=TRUE)))
}
if(yaxis.right){
exp <- c(exp,
# right y-axis labels
expression(text(xlim[2], y_grid_lines(get_ylim()[[2]]),
noquote(format(y_grid_lines(get_ylim()[[2]]), justify="right")),
col=theme$labels, srt=theme$srt, offset=1, pos=4,
cex=theme$cex.axis, xpd=TRUE)))
}
# ylab
exp <- c(exp, expression(title(ylab = ylab[1], mgp = c(1, 1, 0))))
cs$add(exp, env=cs$Env, expr=TRUE)
# add main series
cs$set_frame(2)
if(isTRUE(multi.panel)){
# We need to plot the first "panel" here because the plot area is
# set up based on the code above
lenv <- cs$new_environment()
lenv$xdata <- cs$Env$xdata[subset,1]
lenv$label <- colnames(cs$Env$xdata[,1])
lenv$type <- cs$Env$type
if(yaxis.same){
lenv$ylim <- cs$Env$constant_ylim
} else {
lenv$ylim <- .perturbConstant(range(cs$Env$xdata[subset,1], na.rm=TRUE))
}
exp <- quote(chart.lines(xdata,
type=type,
lty=lty,
lwd=lwd,
lend=lend,
col=theme$col,
up.col=theme$up.col,
dn.col=theme$dn.col,
legend.loc=legend.loc))
exp <- as.expression(add.par.from.dots(exp, ...))
# Add expression for the main plot
cs$add(exp, env=lenv, expr=TRUE)
text.exp <- expression(text(x=get_xcoords()[2],
y=ylim[2]*0.9,
labels=label,
col=theme$labels,
adj=c(0,0),cex=1,offset=0,pos=4))
cs$add(text.exp,env=lenv,expr=TRUE)
if(NCOL(cs$Env$xdata) > 1){
for(i in 2:NCOL(cs$Env$xdata)){
# create a local environment
lenv <- cs$new_environment()
lenv$xdata <- cs$Env$xdata[subset,i]
lenv$label <- cs$Env$column_names[i]
if(yaxis.same){
lenv$ylim <- cs$Env$constant_ylim
} else {
lenv$ylim <- .perturbConstant(range(cs$Env$xdata[subset,i], na.rm=TRUE))
}
lenv$type <- cs$Env$type
# allow color and line attributes for each panel in a multi.panel plot
lenv$lty <- cs$Env$lty[i]
lenv$lwd <- cs$Env$lwd[i]
lenv$col <- cs$Env$theme$col[i]
# Add a small frame
cs$add_frame(ylim=c(0,1),asp=0.25)
cs$next_frame()
text.exp <- expression(text(x=xlim[1],
y=0.5,
labels="",
adj=c(0,0),cex=0.9,offset=0,pos=4))
cs$add(text.exp, env=lenv, expr=TRUE)
# Add the frame for the sub-plots
cs$add_frame(ylim=lenv$ylim, asp=NCOL(cs$Env$xdata), fixed=TRUE)
cs$next_frame()
exp <- quote(chart.lines(xdata[xsubset],
type=type,
lty=lty,
lwd=lwd,
lend=lend,
col=col,
up.col=theme$up.col,
dn.col=theme$dn.col,
legend.loc=legend.loc))
exp <- as.expression(add.par.from.dots(exp, ...))
# NOTE 'exp' was defined earlier as chart.lines
exp <- c(exp,
# y-axis grid lines
expression(segments(xlim[1],
y_grid_lines(ylim),
xlim[2],
y_grid_lines(ylim),
col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty)),
# x-axis grid lines
expression(x_grid_lines(xdata[xsubset], grid.ticks.on, ylim)))
if(yaxis.left){
exp <- c(exp,
# y-axis labels/boxes
expression(text(xlim[1], y_grid_lines(ylim),
noquote(format(y_grid_lines(ylim),justify="right")),
col=theme$labels, srt=theme$srt, offset=1,
pos=2, cex=theme$cex.axis, xpd=TRUE)))
}
if(yaxis.right){
exp <- c(exp,
expression(text(xlim[2], y_grid_lines(ylim),
noquote(format(y_grid_lines(ylim),justify="right")),
col=theme$labels, srt=theme$srt, offset=1,
pos=4, cex=theme$cex.axis, xpd=TRUE)))
}
cs$add(exp,env=lenv,expr=TRUE,no.update=TRUE)
text.exp <- expression(text(x=get_xcoords()[2],
y=ylim[2]*0.9,
labels=label,
col=theme$labels,
adj=c(0,0),cex=1,offset=0,pos=4))
cs$add(text.exp,env=lenv,expr=TRUE)
}
}
} else {
if(type == "h" && NCOL(x) > 1)
warning("only the univariate series will be plotted")
exp <- quote(chart.lines(xdata[xsubset],
type=type,
lty=lty,
lwd=lwd,
lend=lend,
col=theme$col,
up.col=theme$up.col,
dn.col=theme$dn.col,
legend.loc=legend.loc))
exp <- as.expression(add.par.from.dots(exp, ...))
cs$add(exp, expr=TRUE)
assign(".xts_chob", cs, .plotxtsEnv)
}
# Plot the panels or default to a simple line chart
if(!is.null(panels) && nchar(panels) > 0) {
panels <- parse(text=panels, srcfile=NULL)
for( p in 1:length(panels)) {
if(length(panels[p][[1]][-1]) > 0) {
cs <- eval(panels[p])
} else {
cs <- eval(panels[p])
}
}
}
assign(".xts_chob", cs, .plotxtsEnv)
cs
}
# apply a function to the xdata in the xts chob and add a panel with the result
addPanel <- function(FUN, main="", on=NA, type="l", col=NULL, lty=1, lwd=1, pch=1, ...){
# get the chob and the raw data (i.e. xdata)
chob <- current.xts_chob()
# xdata will be passed as first argument to FUN
xdata <- chob$Env$xdata
fun <- match.fun(FUN)
.formals <- formals(fun)
if("..." %in% names(.formals)) {
# Just call do.call if FUN has '...'
x <- try(do.call(fun, c(list(xdata), list(...)), quote=TRUE), silent=TRUE)
} else {
# Otherwise, ensure we only pass relevant args to FUN
.formals <- modify.args(formals=.formals, arglist=list(...))
.formals[[1]] <- quote(xdata)
x <- try(do.call(fun, .formals), silent=TRUE)
}
if(inherits(x, "try-error")) {
message(paste("FUN function failed with message", x))
return(NULL)
}
addSeriesCall <- quote(addSeries(x = x, main = main, on = on,
type = type, col = col, lty = lty, lwd = lwd, pch = pch))
addSeriesCall <- add.par.from.dots(addSeriesCall, ...)
eval(addSeriesCall)
}
# Add a time series to an existing xts plot
# author: Ross Bennett
addSeries <- function(x, main="", on=NA, type="l", col=NULL, lty=1, lwd=1, pch=1, ...){
plot_object <- current.xts_chob()
lenv <- plot_object$new_environment()
lenv$main <- main
lenv$plot_lines <- function(x, ta, on, type, col, lty, lwd, pch, ...){
xdata <- x$Env$xdata
xsubset <- x$Env$xsubset
xDataSubset <- xdata[xsubset]
if(all(is.na(on))){
# Add x-axis grid lines
x$Env$x_grid_lines(xDataSubset, x$Env$grid.ticks.on, par("usr")[3:4])
}
# we can add points that are not necessarily at the points
# on the main series, but need to ensure the new series only
# has index values within the xdata subset
if(xsubset == "") {
subset.range <- xsubset
} else {
fmt <- "%Y-%m-%d %H:%M:%OS6"
subset.range <- paste(format(start(xDataSubset), fmt),
format(end(xDataSubset), fmt), sep = "/")
}
xds <- .xts(, .index(xDataSubset), tzone=tzone(xdata))
ta.y <- merge(ta, xds)[subset.range]
if (!isTRUE(x$Env$extend.xaxis)) {
xi <- .index(ta.y)
xc <- .index(xds)
xsubset <- which(xi >= xc[1] & xi <= xc[length(xc)])
ta.y <- ta.y[xsubset]
}
chart.lines(ta.y, type=type, col=col, lty=lty, lwd=lwd, pch=pch, ...)
}
# get tag/value from dots
expargs <- substitute(alist(ta=x,
on=on,
type=type,
col=col,
lty=lty,
lwd=lwd,
pch=pch,
...))
# capture values from caller, so we don't need to copy objects to lenv,
# since this gives us evaluated versions of all the object values
expargs <- lapply(expargs[-1L], eval, parent.frame())
exp <- as.call(c(quote(plot_lines),
x = quote(current.xts_chob()),
expargs))
plot_object$add_call(match.call())
xdata <- plot_object$Env$xdata
xsubset <- plot_object$Env$xsubset
no.update <- FALSE
lenv$xdata <- merge(x,xdata,retside=c(TRUE,FALSE))
if(hasArg("ylim")) {
ylim <- eval.parent(substitute(alist(...))$ylim)
} else {
ylim <- range(lenv$xdata[xsubset], na.rm=TRUE)
if(all(ylim == 0)) ylim <- c(-1, 1)
}
lenv$ylim <- ylim
if(is.na(on[1])){
# add the frame for drawdowns info
plot_object$add_frame(ylim=c(0,1),asp=0.25)
plot_object$next_frame()
text.exp <- expression(text(x=xlim[1], y=0.3, labels=main,
col=1,adj=c(0,0),cex=0.9,offset=0,pos=4))
plot_object$add(text.exp, env=lenv, expr=TRUE)
# add frame for the data
plot_object$add_frame(ylim=ylim,asp=1,fixed=TRUE)
plot_object$next_frame()
# NOTE 'exp' was defined earlier as chart.lines
exp <- c(exp,
# y-axis grid lines
expression(segments(xlim[1],
y_grid_lines(ylim),
xlim[2],
y_grid_lines(ylim),
col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty)))
if(plot_object$Env$theme$lylab){
exp <- c(exp,
# y-axis labels/boxes
expression(text(xlim[1]-xstep*2/3-max(strwidth(y_grid_lines(ylim))),
y_grid_lines(ylim),
noquote(format(y_grid_lines(ylim),justify="right")),
col=theme$labels, srt=theme$srt, offset=0,
pos=4, cex=theme$cex.axis, xpd=TRUE)))
}
if(plot_object$Env$theme$rylab){
exp <- c(exp,
expression(text(xlim[2]+xstep*2/3,
y_grid_lines(ylim),
noquote(format(y_grid_lines(ylim),justify="right")),
col=theme$labels, srt=theme$srt, offset=0,
pos=4, cex=theme$cex.axis, xpd=TRUE)))
}
plot_object$add(exp,env=lenv,expr=TRUE,no.update=TRUE)
} else {
for(i in 1:length(on)) {
plot_object$set_frame(2*on[i]) # this is defaulting to using headers, should it be optionable?
plot_object$add(exp,env=lenv,expr=TRUE,no.update=no.update)
}
}
plot_object
}
# Add time series of lines to an existing xts plot
# author: Ross Bennett
lines.xts <- function(x, ..., main="", on=0, col=NULL, type="l", lty=1, lwd=1, pch=1){
if(!is.na(on[1]))
if(on[1] == 0) on[1] <- current_panel()
addSeries(x, ...=..., main=main, on=on, type=type, col=col, lty=lty, lwd=lwd, pch=pch)
}
# Add time series of points to an existing xts plot
# author: Ross Bennett
points.xts <- function(x, ..., main="", on=0, col=NULL, pch=1){
if(!is.na(on[1]))
if(on[1] == 0) on[1] <- current_panel()
addSeries(x, ...=..., main=main, on=on, type="p", col=col, pch=pch)
}
# Add vertical lines to an existing xts plot
# author: Ross Bennett
addEventLines <- function(events, main="", on=0, lty=1, lwd=1, col=1, ...){
events <- try.xts(events)
if(!is.na(on[1]))
if(on[1] == 0) on[1] <- current_panel()
if(nrow(events) > 1){
if(length(lty) == 1) lty <- rep(lty, nrow(events))
if(length(lwd) == 1) lwd <- rep(lwd, nrow(events))
if(length(col) == 1) col <- rep(col, nrow(events))
}
plot_object <- current.xts_chob()
lenv <- plot_object$new_environment()
lenv$main <- main
lenv$plot_event_lines <- function(x, events, on, lty, lwd, col, ...){
xdata <- x$Env$xdata
xsubset <- x$Env$xsubset
if(all(is.na(on))){
# Add x-axis grid lines
x$Env$x_grid_lines(xdata[xsubset], x$Env$grid.ticks.on, par("usr")[3:4])
}
ypos <- x$Env$ylim[[2*on]][2]*0.995
# we can add points that are not necessarily at the points on the main series
subset.range <-
paste(format(start(xdata[xsubset]), "%Y%m%d %H:%M:%OS6"),
format(end(xdata[xsubset]), "%Y%m%d %H:%M:%OS6"),
sep = "/")
ta.adj <- merge(n=.xts(1:NROW(xdata[xsubset]),
.index(xdata[xsubset]),
tzone=tzone(xdata)),
.xts(rep(1, NROW(events)),# use numeric for the merge
.index(events)))[subset.range]
# should we not merge and only add events that are in index(xdata)?
ta.y <- ta.adj[,-1]
# the merge should result in NAs for any object that is not in events
event.ind <- which(!is.na(ta.y))
abline(v=x$get_xcoords()[event.ind], col=col, lty=lty, lwd=lwd)
text(x=x$get_xcoords()[event.ind], y=ypos,
labels=as.character(events[,1]),
col=x$Env$theme$labels, ...)
}
# get tag/value from dots
expargs <- substitute(alist(events=events,
on=on,
lty=lty,
lwd=lwd,
col=col,
...))
# capture values from caller, so we don't need to copy objects to lenv,
# since this gives us evaluated versions of all the object values
expargs <- lapply(expargs[-1L], eval, parent.frame())
exp <- as.call(c(quote(plot_event_lines),
x = quote(current.xts_chob()),
expargs))
plot_object$add_call(match.call())
if(is.na(on[1])){
xdata <- plot_object$Env$xdata
xsubset <- plot_object$Env$xsubset
no.update <- FALSE
lenv$xdata <- xdata
ylim <- range(xdata[xsubset], na.rm=TRUE)
lenv$ylim <- ylim
# add the frame for drawdowns info
plot_object$add_frame(ylim=c(0,1),asp=0.25)
plot_object$next_frame()
text.exp <- expression(text(x=xlim[1], y=0.3, labels=main,
col=1,adj=c(0,0),cex=0.9,offset=0,pos=4))
plot_object$add(text.exp, env=lenv, expr=TRUE)
# add frame for the data
plot_object$add_frame(ylim=ylim,asp=1,fixed=TRUE)
plot_object$next_frame()
# NOTE 'exp' was defined earlier as chart.lines
exp <- c(exp,
# y-axis grid lines
expression(segments(xlim[1],
y_grid_lines(ylim),
xlim[2],
y_grid_lines(ylim),
col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty)))
if(plot_object$Env$theme$lylab){
exp <- c(exp,
# y-axis labels/boxes
expression(text(xlim[1]-xstep*2/3-max(strwidth(y_grid_lines(ylim))),
y_grid_lines(ylim),
noquote(format(y_grid_lines(ylim),justify="right")),
col=theme$labels, srt=theme$srt, offset=0,
pos=4, cex=theme$cex.axis, xpd=TRUE)))
}
if(plot_object$Env$theme$rylab){
exp <- c(exp,
expression(text(xlim[2]+xstep*2/3,
y_grid_lines(ylim),
noquote(format(y_grid_lines(ylim),justify="right")),
col=theme$labels, srt=theme$srt, offset=0,
pos=4, cex=theme$cex.axis, xpd=TRUE)))
}
plot_object$add(exp,env=lenv,expr=TRUE,no.update=TRUE)
} else {
for(i in 1:length(on)) {
no.update <- FALSE
plot_object$set_frame(2*on[i]) # this is defaulting to using headers, should it be optionable?
plot_object$add(exp,env=lenv,expr=TRUE,no.update=no.update)
}
}
plot_object
}
# Add legend to an existing xts plot
# author: Ross Bennett
addLegend <- function(legend.loc="topright", legend.names=NULL, col=NULL, ncol=1, on=0, ...){
if(!is.na(on[1]))
if(on[1] == 0) on[1] <- current_panel()
plot_object <- current.xts_chob()
lenv <- plot_object$new_environment()
lenv$plot_legend <- function(x, legend.loc, legend.names, col, ncol, on, bty, text.col, ...){
if(is.na(on[1])){
yrange <- c(0, 1)
} else {
yrange <- x$Env$ylim[[2*on]]
}
# this just gets the data of the main plot
# TODO: get the data of frame[on]
if(is.null(ncol)){
ncol <- NCOL(x$Env$xdata)
}
if(is.null(col)){
col <- x$Env$theme$col[1:NCOL(x$Env$xdata)]
}
if(is.null(legend.names)){
legend.names <- x$Env$column_names
}
if(missing(bty)){
bty <- "n"
}
if(missing(text.col)){
text.col <- x$Env$theme$labels
}
lc <- legend.coords(legend.loc, x$Env$xlim, yrange)
legend(x=lc$x, y=lc$y, legend=legend.names, xjust=lc$xjust, yjust=lc$yjust,
ncol=ncol, col=col, bty=bty, text.col=text.col, ...)
}
# store the call
plot_object$add_call(match.call())
# get tag/value from dots
expargs <- substitute(alist(legend.loc=legend.loc,
legend.names=legend.names,
col=col,
ncol=ncol,
on=on,
...))
# capture values from caller, so we don't need to copy objects to lenv,
# since this gives us evaluated versions of all the object values
expargs <- lapply(expargs[-1L], eval, parent.frame())
exp <- as.call(c(quote(plot_legend),
x = quote(current.xts_chob()),
expargs))
# if on[1] is NA, then add a new frame for the legend
if(is.na(on[1])){
# add frame for spacing
plot_object$add_frame(ylim=c(0,1),asp=0.25)
plot_object$next_frame()
text.exp <- expression(text(x=xlim[1], y=0.3, labels=main,
col=theme$labels,adj=c(0,0),cex=0.9,offset=0,pos=4))
plot_object$add(text.exp, env=lenv, expr=TRUE)
# add frame for the legend panel
plot_object$add_frame(ylim=c(0,1),asp=0.8,fixed=TRUE)
plot_object$next_frame()
# add plot_legend expression
plot_object$add(exp,env=lenv,expr=TRUE,no.update=TRUE)
} else {
for(i in 1:length(on)) {
no.update <- FALSE
plot_object$set_frame(2*on[i]) # this is defaulting to using headers, should it be optionable?
plot_object$add(exp,env=lenv,expr=TRUE,no.update=no.update)
}
}
plot_object
}
# Determine legend coordinates based on legend location,
# range of x values and range of y values
legend.coords <- function(legend.loc, xrange, yrange) {
switch(legend.loc,
topleft = list(xjust = 0, yjust = 1, x = xrange[1], y = yrange[2]),
left = list(xjust = 0, yjust = 0.5, x = xrange[1], y = sum(yrange) / 2),
bottomleft = list(xjust = 0, yjust = 0, x = xrange[1], y = yrange[1]),
top = list(xjust = 0.5, yjust = 1, x = (xrange[1] + xrange[2]) / 2, y = yrange[2]),
center = list(xjust = 0.5, yjust = 0.5, x = (xrange[1] + xrange[2]) / 2, y = sum(yrange) / 2),
bottom = list(xjust = 0.5, yjust = 0, x = (xrange[1] + xrange[2]) / 2, y = yrange[1]),
topright = list(xjust = 1, yjust = 1, x = xrange[2], y = yrange[2]),
right = list(xjust = 1, yjust = 0.5, x = xrange[2], y = sum(yrange) / 2),
bottomright = list(xjust = 1, yjust = 0, x = xrange[2], y = yrange[1])
)
}
# Add a polygon to an existing xts plot
# author: Ross Bennett
addPolygon <- function(x, y=NULL, main="", on=NA, col=NULL, ...){
# add polygon to xts plot based on http://dirk.eddelbuettel.com/blog/2011/01/16/
# some simple checks
x <- try.xts(x)
if(!is.null(y)) stop("y is not null")
if(ncol(x) > 2) warning("more than 2 columns detected in x, only the first 2 will be used")
plot_object <- current.xts_chob()
lenv <- plot_object$new_environment()
lenv$main <- main
lenv$plot_lines <- function(x, ta, on, col, ...){
xdata <- x$Env$xdata
xsubset <- x$Env$xsubset
if(is.null(col)) col <- x$Env$theme$col
if(all(is.na(on))){
# Add x-axis grid lines
x$Env$x_grid_lines(xdata[xsubset], x$Env$grid.ticks.on, par("usr")[3:4])
}
# we can add points that are not necessarily at the points
# on the main series
subset.range <- paste(start(xdata[xsubset]),
end(xdata[xsubset]),sep="/")
ta.adj <- merge(n=.xts(1:NROW(xdata[xsubset]),
.index(xdata[xsubset]),
tzone=tzone(xdata)),ta)[subset.range]
# NAs in the coordinates break the polygon which is not the behavior we want
ta.y <- na.omit(ta.adj[,-1])
n <- NROW(ta.y)
# x coordinates
xx <- .index(ta.y)[c(1,1:n,n:1)]
# y coordinates upper and lower
# assume first column is upper and second column is lower y coords for
# initial prototype
yu <- as.vector(coredata(ta.y[,1]))
yl <- as.vector(coredata(ta.y[,2]))
polygon(x=xx, y=c(yl[1], yu, rev(yl)), border=NA, col=col, ...)
}
# get tag/value from dots
expargs <- substitute(alist(ta=x,
col=col,
on=on,
...))
# capture values from caller, so we don't need to copy objects to lenv,
# since this gives us evaluated versions of all the object values
expargs <- lapply(expargs[-1L], eval, parent.frame())
exp <- as.call(c(quote(plot_lines),
x = quote(current.xts_chob()),
expargs))
plot_object$add_call(match.call())
xdata <- plot_object$Env$xdata
xsubset <- plot_object$Env$xsubset
no.update <- FALSE
lenv$xdata <- merge(x,xdata,retside=c(TRUE,FALSE))
if(hasArg("ylim")) {
ylim <- eval.parent(substitute(alist(...))$ylim)