/
gg-plots.R
1876 lines (1652 loc) · 54.4 KB
/
gg-plots.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
# add global variable
if (getRversion() >= "2.15.1") {
utils::globalVariables(unique(c(
"labelp", # cor plot
c("..density..", "..scaled..", "x"), # facetdensitystrip plot
c("..scaled..", "x"), #density diagonal plot
c("x", "y", "lab"), # internal axis plot
c("x", "y", "result", "freq"), # fluctuation plot
c("weight") # ggally_summarise_by
)))
}
# retrieve the evaulated data column given the aes (which could possibly do operations)
#' Evaluate data column
#' @param data data set to evaluate the data with
#' @param aes_col Single value from an \code{ggplot2::\link[ggplot2]{aes}(...)} object
#' @return Aes mapping with the x and y values switched
#' @export
#' @examples
#' mapping <- ggplot2::aes(Petal.Length)
#' eval_data_col(iris, mapping$x)
eval_data_col <- function(data, aes_col) {
rlang::eval_tidy(aes_col, data)
}
#' Aes name
#' @param aes_col Single value from \code{ggplot2::\link[ggplot2]{aes}(...)}
#' @return character string
#' @export
#' @examples
#' mapping <- ggplot2::aes(Petal.Length)
#' mapping_string(mapping$x)
mapping_string <- function(aes_col) {
gsub("^~", "", deparse(aes_col, 500L))
}
# is categories on the left?
#' Check if plot is horizontal
#'
#' @param data data used in ggplot2 plot
#' @param mapping ggplot2 \code{aes()} mapping
#' @param val key to retrieve from \code{mapping}
#' @return Boolean determining if the data is a character-like data
#' @export
#' @rdname is_horizontal
#' @examples
#' is_horizontal(iris, ggplot2::aes(Sepal.Length, Species)) # TRUE
#' is_horizontal(iris, ggplot2::aes(Sepal.Length, Species), "x") # FALSE
#' is_horizontal(iris, ggplot2::aes(Sepal.Length, Sepal.Width)) # FALSE
is_horizontal <- function(data, mapping, val = "y") {
yData <- eval_data_col(data, mapping[[val]])
is.factor(yData) || is.character(yData) || is.logical(yData)
}
#' @export
#' @rdname is_horizontal
is_character_column <- is_horizontal
#' Swap x and y mapping
#' @param mapping output of \code{ggplot2::\link[ggplot2]{aes}(...)}
#' @return Aes mapping with the x and y values switched
#' @export
#' @examples
#' mapping <- ggplot2::aes(Petal.Length, Sepal.Width)
#' mapping
#' mapping_swap_x_y(mapping)
mapping_swap_x_y <- function(mapping) {
tmp <- mapping$x
mapping$x <- mapping$y
mapping$y <- tmp
mapping
}
#' Remove colour mapping unless found in select mapping keys
#' @param mapping output of \code{ggplot2::\link[ggplot2]{aes}(...)}
#' @param to set of mapping keys to check
#' @return Aes mapping with colour mapping kept only if found in selected mapping keys.
#' @export
#' @examples
#' mapping <- aes(x = sex, y = age, colour = sex)
# remove_color_unless_equal(mapping, to = c("x", "y"))
# remove_color_unless_equal(mapping, to = c("y"))
#'
#' mapping <- aes(x = sex, y = age, colour = region)
#' remove_color_unless_equal(mapping)
remove_color_unless_equal <- function(mapping, to = c("x", "y")) {
if (!is.null(mapping$colour)) {
color_str <- mapping_string(mapping$colour)
for (to_val in to) {
to_str <- mapping_string(mapping[[to_val]])
if (color_str == to_str) {
# found! return
return(mapping)
}
}
# not found. Remove color value
mapping <- mapping[names(mapping) != "colour"]
}
mapping
}
#' Scatter plot
#'
#' Make a scatter plot with a given data set.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... other arguments are sent to geom_point
#' @author Barret Schloerke
#' @export
#' @keywords hplot
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(mtcars)
#' p_(ggally_points(mtcars, mapping = ggplot2::aes(x = disp, y = hp)))
#' p_(ggally_points(mtcars, mapping = ggplot2::aes_string(x = "disp", y = "hp")))
#' p_(ggally_points(
#' mtcars,
#' mapping = ggplot2::aes_string(
#' x = "disp",
#' y = "hp",
#' color = "as.factor(cyl)",
#' size = "gear"
#' )
#' ))
ggally_points <- function(data, mapping, ...) {
p <- ggplot(data = data, mapping = mapping) + geom_point(...)
p
}
#' Scatter plot with a smoothed line
#'
#' Add a smoothed condition mean with a given scatter plot.
#'
#' Y limits are reduced to match original Y range with the goal of keeping the Y axis the same across plots.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param formula,... other arguments to add to geom_smooth
#' @param method,se parameters supplied to \code{\link[ggplot2]{geom_smooth}}
#' @param shrink boolean to determine if y range is reduced to range of points or points and error ribbon
#' @author Barret Schloerke
#' @export
#' @keywords hplot
#' @rdname ggally_smooth
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_smooth(tips, mapping = ggplot2::aes(x = total_bill, y = tip)))
#' p_(ggally_smooth(tips, mapping = ggplot2::aes_string(x = "total_bill", y = "tip")))
#' p_(ggally_smooth(tips, mapping = ggplot2::aes_string(x = "total_bill", y = "tip", color = "sex")))
ggally_smooth <- function(data, mapping, ..., method = "lm", formula = y ~ x, se = TRUE, shrink = TRUE) {
p <- ggplot(data = data, mapping)
p <- p + geom_point(...)
if (! is.null(mapping$color) || ! is.null(mapping$colour)) {
p <- p + geom_smooth(method = method, se = se, formula = formula)
} else {
p <- p + geom_smooth(method = method, se = se, formula = formula, colour = I("black"))
}
if (isTRUE(shrink)) {
p <- p +
coord_cartesian(
ylim = range(eval_data_col(data, mapping$y), na.rm = TRUE)
)
}
p
}
#' @export
#' @rdname ggally_smooth
ggally_smooth_loess <- function(data, mapping, ...) {
ggally_smooth(data = data, mapping = mapping, ..., method = "loess")
}
#' @export
#' @rdname ggally_smooth
ggally_smooth_lm <- function(data, mapping, ...) {
ggally_smooth(data = data, mapping = mapping, ..., method = "lm")
}
#' Bivariate density plot
#'
#' Make a 2D density plot from a given data.
#'
#' The aesthetic "fill" determines whether or not \code{stat_density2d} (filled) or \code{geom_density2d} (lines) is used.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... parameters sent to either stat_density2d or geom_density2d
#' @author Barret Schloerke
#' @export
#' @keywords hplot
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_density(tips, mapping = ggplot2::aes(x = total_bill, y = tip)))
#' p_(ggally_density(tips, mapping = ggplot2::aes_string(x = "total_bill", y = "tip")))
#' p_(ggally_density(
#' tips,
#' mapping = ggplot2::aes_string(x = "total_bill", y = "tip", fill = "..level..")
#' ))
#' p_(ggally_density(
#' tips,
#' mapping = ggplot2::aes_string(x = "total_bill", y = "tip", fill = "..level..")
#' ) + ggplot2::scale_fill_gradient(breaks = c(0.05, 0.1, 0.15, 0.2)))
ggally_density <- function(data, mapping, ...) {
rangeX <- range(eval_data_col(data, mapping$x), na.rm = TRUE)
rangeY <- range(eval_data_col(data, mapping$y), na.rm = TRUE)
p <- ggplot(data = data) +
geom_point(
data = data.frame(rangeX = rangeX, rangeY = rangeY),
mapping = aes(x = rangeX, y = rangeY),
alpha = 0
)
if (!is.null(mapping$fill)) {
p <- p + stat_density2d(mapping = mapping, geom = "polygon", ...)
} else {
p <- p + geom_density2d(mapping = mapping, ...)
}
p
}
#' Correlation value plot
#'
#' Estimate correlation from the given data. If a color variable is supplied, the correlation will also be calculated per group.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... other arguments being supplied to \code{\link[ggplot2]{geom_text}()} for the title and groups
#' @param stars logical value which determines if the significance stars should be displayed. Given the \code{\link[stats]{cor.test}} p-values, display \describe{
#' \item{\code{"***"}}{if the p-value is \verb{< 0.001}}
#' \item{\code{"**"}}{if the p-value is \verb{< 0.01}}
#' \item{\code{"*"}}{if the p-value is \verb{< 0.05}}
#' \item{\code{"."}}{if the p-value is \verb{< 0.10}}
#' \item{\code{""}}{otherwise}
#' }
#' @param method \code{method} supplied to cor function
#' @param use \code{use} supplied to \code{\link[stats]{cor}} function
#' @param display_grid if \code{TRUE}, display aligned panel grid lines. If \code{FALSE} (default), display a thin panel border.
#' @param digits number of digits to be displayed after the decimal point. See \code{\link[base]{formatC}} for how numbers are calculated.
#' @param title_args arguments being supplied to the title's \code{\link[ggplot2]{geom_text}()}
#' @param group_args arguments being supplied to the split-by-color group's \code{\link[ggplot2]{geom_text}()}
#' @param justify_labels \code{justify} argument supplied when \code{\link[base]{format}}ting the labels
#' @param align_percent relative align position of the text. When \code{justify_labels = 0.5}, this should not be needed to be set.
#' @param alignPercent,displayGrid deprecated. Please use their snake-case counterparts.
#' @param title title text to be displayed
#' @author Barret Schloerke
#' @importFrom stats complete.cases cor
#' @seealso \code{\link{ggally_statistic}}, \code{\link{ggally_cor_v1_5}}
#' @export
#' @keywords hplot
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_cor(tips, mapping = ggplot2::aes_string(x = "total_bill", y = "tip")))
#' # display with grid
#' p_(ggally_cor(
#' tips,
#' mapping = ggplot2::aes_string(x = "total_bill", y = "tip"),
#' display_grid = TRUE
#' ))
#' # change text attributes
#' p_(ggally_cor(
#' tips,
#' mapping = ggplot2::aes(x = total_bill, y = tip),
#' size = 15,
#' colour = I("red"),
#' title = "Correlation"
#' ))
#' # split by a variable
#' p_(ggally_cor(
#' tips,
#' mapping = ggplot2::aes_string(x = "total_bill", y = "tip", color = "sex"),
#' size = 5
#' ))
ggally_cor <- function(
data,
mapping,
...,
stars = TRUE,
method = "pearson",
use = "complete.obs",
display_grid = FALSE,
digits = 3,
title_args = list(...),
group_args = list(...),
justify_labels = "right",
align_percent = 0.5,
title = "Corr",
alignPercent = warning("deprecated. Use `align_percent`"),
displayGrid = warning("deprecated. Use `display_grid`")
) {
if (!missing(alignPercent)) {
warning("`alignPercent` is deprecated. Please use `align_percent` if alignment still needs to be adjusted")
align_percent <- alignPercent
}
if (!missing(displayGrid)) {
warning("`displayGrid` is deprecated. Please use `display_grid`")
display_grid <- displayGrid
}
na.rm <-
if (missing(use)) {
# display warnings
NA
} else {
(use %in% c("complete.obs", "pairwise.complete.obs", "na.or.complete"))
}
ggally_statistic(
data = data,
mapping = mapping,
na.rm = na.rm,
align_percent = align_percent,
display_grid = display_grid,
title_args = title_args,
group_args = group_args,
justify_labels = justify_labels,
justify_text = "left",
sep = if ("colour" %in% names(mapping)) ": " else ":\n",
title = title,
text_fn = function(x, y) {
if (is_date(x)) {
x <- as.numeric(x)
}
if (is_date(y)) {
y <- as.numeric(y)
}
corObj <- stats::cor.test(x, y, method = method, use = use)
# make sure all values have X-many decimal places
cor_est <- as.numeric(corObj$estimate)
cor_txt <- formatC(cor_est, digits = digits, format = "f")
# if stars should be added
if (isTRUE(stars)) {
cor_txt <- str_c(
cor_txt,
signif_stars(corObj$p.value)
)
}
cor_txt
}
)
}
#' Generalized text display
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param title title text to be displayed
#' @param text_fn function that takes in \code{x} and \code{y} and returns a text string
#' @param na.rm logical value which determines if \code{NA} values are removed. If \code{TRUE}, no warning message will be displayed.
#' @param display_grid if \code{TRUE}, display aligned panel grid lines. If \code{FALSE} (default), display a thin panel border.
#' @param justify_labels \code{justify} argument supplied when \code{\link[base]{format}}ting the labels
#' @param justify_text \code{justify} argument supplied when \code{\link[base]{format}}ting the returned \code{text_fn(x, y)} values
#' @param sep separation value to be placed between the labels and text
#' @param family font family used when displaying all text. This value will be set in \code{title_args} or \code{group_args} if no \code{family} value exists. By using \code{"mono"}, groups will align with each other.
#' @param title_args arguments being supplied to the title's \code{\link[ggplot2]{geom_text}()}
#' @param group_args arguments being supplied to the split-by-color group's \code{\link[ggplot2]{geom_text}()}
#' @param align_percent relative align position of the text. When \code{title_hjust = 0.5} and \code{group_hjust = 0.5}, this should not be needed to be set.
#' @param title_hjust,group_hjust \code{hjust} sent to \code{\link[ggplot2]{geom_text}()} for the title and group values respectively. Any \code{hjust} value supplied in \code{title_args} or \code{group_args} will take precedence.
#' @seealso \code{\link{ggally_cor}}
#' @export
ggally_statistic <- function(
data,
mapping,
text_fn,
title,
na.rm = NA,
display_grid = FALSE,
justify_labels = "right",
justify_text = "left",
sep = ": ",
family = "mono",
title_args = list(),
group_args = list(),
align_percent = 0.5,
title_hjust = 0.5,
group_hjust = 0.5
) {
set_if_not_there <- function(obj, key, value) {
obj <- as.list(obj)
#if (! "family" %in% rlang::names2(obj)) {
# obj$family <- family
#}
obj
}
#title_args <- set_if_not_there(title_args, "family", family)
#group_args <- set_if_not_there(group_args, "family", family)
title_args <- set_if_not_there(title_args, "hjust", title_hjust)
group_args <- set_if_not_there(group_args, "hjust", group_hjust)
xData <- eval_data_col(data, mapping$x)
yData <- eval_data_col(data, mapping$y)
colorData <- eval_data_col(data, mapping$colour)
if (is.numeric(colorData)) {
stop("`mapping` color column must be categorical, not numeric")
}
display_na_rm <- is.na(na.rm)
if (display_na_rm) {
na.rm <- TRUE
}
if (isTRUE(na.rm)) {
if (!is.null(colorData) && (length(colorData) == length(xData))) {
rows <- complete.cases(xData, yData, colorData)
} else {
rows <- complete.cases(xData, yData)
}
if (any(!rows)) {
if (!is.null(colorData) && (length(colorData) == length(xData))) {
colorData <- colorData[rows]
}
xData <- xData[rows]
yData <- yData[rows]
if (isTRUE(display_na_rm)) {
total <- sum(!rows)
if (total > 1) {
warning("Removed ", total, " rows containing missing values")
} else if (total == 1) {
warning("Removing 1 row that contained a missing value")
}
}
}
}
xVal <- xData
yVal <- yData
# if the mapping has to deal with the data, remove it
### IDK what this does. inherited from old code.
for (mappingName in names(mapping)) {
itemData <- eval_data_col(data, mapping[[mappingName]])
if (!inherits(itemData, "AsIs")) {
mapping[[mappingName]] <- NULL
}
}
### END IDK
# calculate variable ranges so the gridlines line up
xValNum <- as.numeric(xVal)
yValNum <- as.numeric(yVal)
xmin <- min(xValNum, na.rm = TRUE)
xmax <- max(xValNum, na.rm = TRUE)
xrange <- c(xmin - 0.01 * (xmax - xmin), xmax + 0.01 * (xmax - xmin))
ymin <- min(yValNum, na.rm = TRUE)
ymax <- max(yValNum, na.rm = TRUE)
yrange <- c(ymin - 0.01 * (ymax - ymin), ymax + 0.01 * (ymax - ymin))
# if there is a color grouping...
if (
!is.null(colorData) &&
!inherits(colorData, "AsIs")
) {
cord <- ddply(
data.frame(x = xData, y = yData, color = colorData),
"color",
function(dt) {
text_fn(dt$x, dt$y)
}
)
colnames(cord)[2] <- "text"
# put in correct order
lev <- levels(as.factor(colorData))
ord <- rep(-1, nrow(cord))
for (i in 1:nrow(cord)) {
for (j in seq_along(lev)) {
if (identical(as.character(cord$color[i]), as.character(lev[j]))) {
ord[i] <- j
}
}
}
cord <- cord[order(ord[ord >= 0]), ]
# make labels align together
cord$label <- str_c(
format(cord$color, justify = justify_labels),
sep,
format(cord$text, justify = justify_text)
)
# title
ggally_text_args <- append(
list(
label = str_c(title, sep, text_fn(xVal, yVal)),
mapping = mapping,
xP = 0.5,
yP = 0.9,
xrange = xrange,
yrange = yrange
),
title_args
)
p <- do.call(ggally_text, ggally_text_args)
xPos <- rep(align_percent, nrow(cord)) * diff(xrange) + min(xrange, na.rm = TRUE)
yPos <- seq(
from = 0.9,
to = 0.2,
length.out = nrow(cord) + 1)
yPos <- yPos * diff(yrange) + min(yrange, na.rm = TRUE)
yPos <- yPos[-1]
cordf <- data.frame(xPos = xPos, yPos = yPos, labelp = cord$label)
cordf$labelp <- factor(cordf$labelp, levels = cordf$labelp)
# group text values
geom_text_args <- append(
list(
data = cordf,
aes(
x = xPos,
y = yPos,
label = labelp,
color = labelp
)
),
group_args
)
p <- p + do.call(geom_text, geom_text_args)
} else {
ggally_text_args <- append(
list(
label = paste0(title, sep, text_fn(xVal, yVal), collapse = ""),
mapping,
xP = 0.5,
yP = 0.5,
xrange = xrange,
yrange = yrange
),
title_args
)
p <- do.call(ggally_text, ggally_text_args)
}
if (!isTRUE(display_grid)) {
p <- p +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_rect(
linetype = "solid",
color = theme_get()$panel.background$fill,
fill = "transparent"
)
)
}
p + theme(legend.position = "none")
}
#' Box plot
#'
#' Make a box plot with a given data set. \code{ggally_box_no_facet} will be a single panel plot, while \code{ggally_box} will be a faceted plot
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... other arguments being supplied to geom_boxplot
#' @author Barret Schloerke
#' @keywords hplot
#' @export
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_box(tips, mapping = ggplot2::aes(x = total_bill, y = sex)))
#' p_(ggally_box(tips, mapping = ggplot2::aes_string(x = "total_bill", y = "sex")))
#' p_(ggally_box(
#' tips,
#' mapping = ggplot2::aes_string(y = "total_bill", x = "sex", color = "sex"),
#' outlier.colour = "red",
#' outlier.shape = 13,
#' outlier.size = 8
#' ))
ggally_box <- function(data, mapping, ...) {
mapping <- mapping_color_to_fill(mapping)
ggally_dot_and_box(data, mapping, ..., boxPlot = TRUE)
}
#' @export
#' @rdname ggally_box
ggally_box_no_facet <- function(data, mapping, ...) {
mapping <- mapping_color_to_fill(mapping)
ggally_dot_and_box_no_facet(data, mapping, ..., boxPlot = TRUE)
}
#' Grouped dot plot
#'
#' Add jittering with the box plot. \code{ggally_dot_no_facet} will be a single panel plot, while \code{ggally_dot} will be a faceted plot
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... other arguments being supplied to geom_jitter
#' @author Barret Schloerke
#' @keywords hplot
#' @export
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_dot(tips, mapping = ggplot2::aes(x = total_bill, y = sex)))
#' p_(ggally_dot(tips, mapping = ggplot2::aes_string(x = "total_bill", y = "sex")))
#' p_(ggally_dot(
#' tips,
#' mapping = ggplot2::aes_string(y = "total_bill", x = "sex", color = "sex")
#' ))
#' p_(ggally_dot(
#' tips,
#' mapping = ggplot2::aes_string(y = "total_bill", x = "sex", color = "sex", shape = "sex")
#' ) + ggplot2::scale_shape(solid = FALSE))
ggally_dot <- function(data, mapping, ...) {
ggally_dot_and_box(data, mapping, ..., boxPlot = FALSE)
}
#' @export
#' @rdname ggally_dot
ggally_dot_no_facet <- function(data, mapping, ...) {
ggally_dot_and_box_no_facet(data, mapping, ..., boxPlot = FALSE)
}
#' Box and dot plot
#'
#' Place box plots or dot plots on the graph
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... parameters passed to either geom_jitter or geom_boxplot
#' @param boxPlot boolean to decide to plot either box plots (TRUE) or dot plots (FALSE)
#' @author Barret Schloerke
#' @keywords internal
#' @export
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_dot_and_box(
#' tips,
#' mapping = ggplot2::aes(x = total_bill, y = sex, color = sex),
#' boxPlot = TRUE
#' ))
#' p_(ggally_dot_and_box(
#' tips,
#' mapping = ggplot2::aes(x = total_bill, y = sex, color = sex),
#' boxPlot = FALSE
#' ))
ggally_dot_and_box <- function(data, mapping, ..., boxPlot = TRUE) {
horizontal <- is_horizontal(data, mapping)
if (horizontal) {
mapping <- mapping_swap_x_y(mapping)
}
xVal <- mapping_string(mapping$x)
p <- ggplot(data = data)
if (boxPlot) {
p <- p + geom_boxplot(mapping, ...)
} else {
p <- p + geom_jitter(mapping, ...)
}
if (!horizontal) {
p <- p +
facet_grid(paste(". ~ ", xVal, sep = ""), scales = "free_x") +
theme(panel.spacing = unit(0.1, "lines"))
} else {
p <- p +
coord_flip() +
facet_grid(paste(xVal, " ~ .", sep = ""), scales = "free_y") +
theme(panel.spacing = unit(0.1, "lines"))
}
p
}
ggally_dot_and_box_no_facet <- function(data, mapping, ..., boxPlot = TRUE) {
horizontal <- is_horizontal(data, mapping)
if (horizontal) {
mapping <- mapping_swap_x_y(mapping)
}
p <- ggplot(data = data)
if (boxPlot) {
p <- p + geom_boxplot(mapping, ...)
} else {
p <- p + geom_jitter(mapping, ...)
}
if (horizontal) {
p <- p +
scale_x_discrete(
limits = rev(levels(eval_data_col(data, mapping$x)))
) +
coord_flip()
}
p
}
#' Faceted histogram
#'
#' Display subsetted histograms of the data in different panels.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... parameters sent to stat_bin()
#' @author Barret Schloerke
#' @keywords hplot
#' @export
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_facethist(tips, mapping = ggplot2::aes(x = tip, y = sex)))
#' p_(ggally_facethist(tips, mapping = ggplot2::aes_string(x = "tip", y = "sex"), binwidth = 0.1))
ggally_facethist <- function(data, mapping, ...) {
mapping <- mapping_color_to_fill(mapping)
horizontal <- is_horizontal(data, mapping)
if (!horizontal) {
mapping <- mapping_swap_x_y(mapping)
}
xVal <- mapping_string(mapping$x)
yVal <- mapping_string(mapping$y)
mapping$y <- NULL
p <- ggplot(data = data, mapping)
p <- p + stat_bin(...)
if (horizontal) {
p <- p +
facet_grid(paste(yVal, " ~ .", sep = "")) +
theme(panel.spacing = unit(0.1, "lines"))
} else {
p <- p +
facet_grid(paste(". ~", yVal, sep = "")) +
theme(panel.spacing = unit(0.1, "lines")) +
coord_flip()
}
p <- p + labs(x = xVal, y = yVal)
p
}
#' Faceted density plot
#'
#' Make density plots by displaying subsets of the data in different panels.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... other arguments being sent to stat_density
#' @author Barret Schloerke
#' @keywords hplot
#' @export
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_facetdensity(tips, mapping = ggplot2::aes(x = total_bill, y = sex)))
#' p_(ggally_facetdensity(
#' tips,
#' mapping = ggplot2::aes_string(y = "total_bill", x = "sex", color = "sex")
#' ))
ggally_facetdensity <- function(data, mapping, ...) {
ggally_facetdensitystrip(data, mapping, ..., den_strip = FALSE)
}
#' Tile plot with facets
#'
#' Displays a Tile Plot as densely as possible.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... other arguments being sent to stat_bin
#' @author Barret Schloerke
#' @keywords hplot
#' @export
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_denstrip(tips, mapping = ggplot2::aes(x = total_bill, y = sex)))
#' p_(ggally_denstrip(tips, mapping = ggplot2::aes_string(x = "total_bill", y = "sex")))
#' p_(ggally_denstrip(
#' tips,
#' mapping = ggplot2::aes_string(x = "sex", y = "tip", binwidth = "0.2")
#' ) + ggplot2::scale_fill_gradient(low = "grey80", high = "black"))
ggally_denstrip <- function(data, mapping, ...) {
mapping <- mapping_color_to_fill(mapping)
ggally_facetdensitystrip(data, mapping, ..., den_strip = TRUE)
}
#' Density or tiles plot with facets
#'
#' Make tile plot or density plot as compact as possible.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... other arguments being sent to either geom_histogram or stat_density
#' @param den_strip boolean to decide whether or not to plot a density strip(TRUE) or a facet density(FALSE) plot.
#' @author Barret Schloerke
#' @keywords hplot
#' @export
#' @examples
#' example(ggally_facetdensity)
#' example(ggally_denstrip)
ggally_facetdensitystrip <- function(data, mapping, ..., den_strip = FALSE) {
horizontal <- is_horizontal(data, mapping)
if (!horizontal) {
mapping <- mapping_swap_x_y(mapping)
}
xVal <- mapping_string(mapping$x)
yVal <- mapping_string(mapping$y)
mappingY <- mapping$y # nolint
mapping$y <- NULL # will be faceted
p <- ggplot(data = data, mapping) + labs(x = xVal, y = yVal)
if (identical(den_strip, TRUE)) {
p <- p +
geom_histogram(
mapping = aes(fill = ..density..), # nolint
position = "fill",
...
) +
scale_y_continuous(
breaks = c(0.5),
labels = "1"
)
} else {
p <- p +
stat_density(
aes(
y = ..scaled.. * diff(range(x, na.rm = TRUE)) + min(x, na.rm = TRUE) # nolint
),
position = "identity",
geom = "line",
...
)
}
if (horizontal) {
p <- p + facet_grid(paste(yVal, " ~ .", sep = ""))
if (identical(den_strip, TRUE)) {
p <- p + theme(axis.text.y = element_blank())
}
} else {
p <- p + coord_flip()
p <- p + facet_grid(paste(". ~ ", yVal, sep = ""))
if (identical(den_strip, TRUE)) {
p <- p + theme(axis.text.x = element_blank())
}
}
p
}
#' Univariate density plot
#'
#' Displays a density plot for the diagonal of a \code{\link{ggpairs}} plot matrix.
#'
#' @param data data set using
#' @param mapping aesthetics being used.
#' @param ... other arguments sent to stat_density
#' @param rescale boolean to decide whether or not to rescale the count output
#' @author Barret Schloerke
#' @keywords hplot
#' @export
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_densityDiag(tips, mapping = ggplot2::aes(x = total_bill)))
#' p_(ggally_densityDiag(tips, mapping = ggplot2::aes(x = total_bill, color = day)))
ggally_densityDiag <- function(data, mapping, ..., rescale = FALSE) {
mapping <- mapping_color_to_fill(mapping)
p <- ggplot(data, mapping) +
scale_y_continuous()
if (identical(rescale, TRUE)) {
p <- p +
stat_density(
aes(
y = ..scaled.. * diff(range(x, na.rm = TRUE)) + min(x, na.rm = TRUE) # nolint
),
position = "identity",
geom = "line",
...
)
} else {
p <- p + geom_density(...)
}
p
}
#' Bar plot
#'
#' Displays a bar plot for the diagonal of a \code{\link{ggpairs}} plot matrix.
#'
#' @param data data set using
#' @param mapping aesthetics being used
#' @param ... other arguments are sent to geom_bar
#' @param rescale boolean to decide whether or not to rescale the count output. Only applies to numeric data
#' @author Barret Schloerke
#' @keywords hplot
#' @export
#' @examples
#' # Small function to display plots only if it's interactive
#' p_ <- GGally::print_if_interactive
#'
#' data(tips, package = "reshape")
#' p_(ggally_barDiag(tips, mapping = ggplot2::aes(x = day)))
#' p_(ggally_barDiag(tips, mapping = ggplot2::aes(x = tip), binwidth = 0.25))
ggally_barDiag <- function(data, mapping, ..., rescale = FALSE) {
mapping <- mapping_color_to_fill(mapping)
mapping$y <- NULL
x_data <- eval_data_col(data, mapping$x)
numer <- ("continuous" == plotting_data_type(x_data))
p <- ggplot(data = data, mapping)