-
Notifications
You must be signed in to change notification settings - Fork 2
/
UsefulCode_ggplot.Rmd
1317 lines (1092 loc) · 35.4 KB
/
UsefulCode_ggplot.Rmd
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
---
title: Useful R code in `ggplot`
author: |
| Matthew Malishev
| @darwinanddavis
fontsize: 10
geometry: margin=1in
documentclass: article
linkcolor: pink
urlcolor: blue
citecolor: red
always_allow_html: yes
output:
html_document:
highlight: tango
code_folding: show
toc: yes
toc_depth: 4
number_sections: no
toc_float: yes
md_document:
variant: markdown_github
pdf_document:
includes:
in_header: # add .tex file with header content
highlight: tango
template: null
toc: yes
toc_depth: 4
number_sections: false
fig_width: 4
fig_height: 5
fig_caption: true
df_print: tibble
citation_package: biblatex # natbib
latex_engine: xelatex #pdflatex # lualatex
keep_tex: true # keep .tex file in dir
word_document:
highlight: tango
keep_md: yes
pandoc_args: --smart
#reference: mystyles.docx
toc: yes
toc_depth: 4
inludes:
before_body: before_body.tex
subtitle:
tags:
- nothing
- nothingness
params:
dir: "/Users/malishev/Documents/Melbourne Uni/Programs/R code/UsefulCode"
date: !r Sys.Date()
version: !r getRversion()
email: "matthew.malishev [at] gmail.com"
doi: https://github.com/darwinanddavis/UsefulCode
classoption: portrait
# ^['https://github.com/darwinanddavis/UsefulCode'] # footnote
vignette: >
%\VignetteIndexEntry{Useful R code}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
---
<script type="text/x-mathjax-config">
MathJax.Hub.Config({ TeX: { equationNumbers: {autoNumber: "all"} } });
</script>
```{r echo = FALSE}
library(rmarkdown)
# setwd("")
# f <- list.files()[1]
# render(f, output_format='pdf_document')
# render(f, output_format='pdf_document')
```
```{r, set-options, echo = FALSE, cache = FALSE}
options(width=100)
knitr::opts_chunk$set(
eval = T, # run all code
results='hide',
# echo = FALSE, # show code chunks in output
comment = "",
tidy.opts=list(width.cutoff=100), # set width of code chunks in output
tidy=TRUE, # make output as tidy
message = FALSE, # mask all messages
warning = FALSE, # mask all warnings
size="small" # set code chunk size
)
# https://github.com/ucb-stat133/stat133-fall-2016/blob/master/hws/hw02-tables-ggplot.Rmd
knitr::opts_knit$set(root.dir=paste0(params$dir,"/")) # set working dir
setwd(paste0(params$dir,"/")) # for running just in R not knitr
```
\
Date: `r params$date`
`R` version: `r params$version`
*Corresponding author: `r params$email`
This document can be found at `r params$doi`
\newpage
## Overview
Same deal as Useful Code 1 and 2 except just `gglot` because it's too difficult sifting through the other docs.
### Remove annoying stock gridlines from plot window
```{r, ggplot1, results='hide',eval=F}
# option 1
p1 <- p + labs(title="Option 1") +
theme_classic()
p1
# option 2 with inputs to toggle
p2 <- p + labs(title="Option 2") +
theme_bw() +
theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")
)
p2
# alternative (after loading ggridges library)
# theme_ridges(grid=F,center_axis_labels = T)
```
### Setting global graphics theme for ggplot
```{r, ggplot2, results='hide',eval=F}
plot_it_now <- function(bg){ # bg = colour to plot bg
theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = bg,
colour = bg),
plot.background = element_rect(fill=bg)
) +
theme(axis.line = element_line(color = "white")) +
theme(axis.ticks = element_line(color = "white")) +
theme(plot.title = element_text(colour = "white")) +
theme(axis.title.x = element_text(colour = "white"),
axis.title.y = element_text(colour = "white")) +
theme(axis.text.x = element_text(color = "white"),
axis.text.y = element_text(color = "white")) +
theme(legend.key = element_rect(fill = bg)) +
theme(legend.title = element_text(colour="white")) +
theme(legend.text = element_text(colour="white"))
}
plot_it_now("black")
```
### Put plot in function to take dynamic data inputs
Ref: http://jcborras.net/carpet/visualizing-political-divergences-2012-local-elections-in-helsinki.html
```{r, ggplot3, results='hide',eval=F}
hr.mass.plot <- function(d) {
p <- ggplot(d, aes(HR, Mass, color = colfunc)) +
geom_density_2d(data=d, aes(x = HR, y = Mass),
stat = "density2d",position="identity",
color=adjustcolor("orange",alpha=0.8), size=1.5, contour = T, lineend="square",linejoin="round")
p <- p + geom_point(data=d, aes(x = HR, y = Mass),
color=colfunc,
fill=colfunc) +
scale_color_manual(values = magma(8))
p <- p + scale_y_continuous(limits=c(-200,200), name="Mass lost (g)")
p <- p + scale_x_continuous(limits=c(0,0.35),name=expression("Home range area (km^2)"))
p <- p + theme_classic()
print(p)
}
hr.mass.plot(d)
```
### Using `ggplot` when looping through `for` loop and saving to dir
```{r, ggplot4,eval=F}
pdf("mypdf.pdf",onefile = T)
for(i in 1:3){
par(bty="n", las = 1)
grid.arrange(
ggplot(data, aes(x = X, y = Y, fill = ..x..)) +
geom_point() +
labs(title = paste0("Title_",i)) +
xlab("X") +
ylab("Y")
)
}
# end loop
dev.off()
# geom_density_ridges() # scale = overlap
# geom_density_ridges(scale = 5, size=0.2,color="white", rel_min_height = 0.01,fill=col,alpha=0.5) +
# scale_fill_viridis option = "magma", "inferno","plasma", "viridis", "cividis"
```
### Converting lists and dataframes to usable format for `ggplot` (`melt` package)
```{r, ggplot5, results='hide',eval=F}
require(reshape2) # melt package
nn <- 10 # reps
mm <- data.frame("X"=rep(LETTERS,nn),"Y"=sample(nn,replace = T),"Z"=rep(paste(LETTERS,"_",rnorm(1)),nn))
# plot
y_m <- melt(mm); head(y_m)
ggplot(data = y_m, aes(x = X, y = value, group = Z, colour=factor(value))) +
geom_point(aes(size=value)) + geom_line() + theme_classic()
```
### Insert math expression in plot or legend title
```{r, ggplot6, results='hide',eval=F}
xx = sample(100, 100)
yy = rnorm(100)
title1 <- bquote("Density = " ~ r[xy] ~ "and" ~ B^2 ~ + beta ~ alpha)
ggplot() +
geom_point(aes(x=xx,y=yy),color=xx) +
labs(title = title1,
xlab = title1,
yab = title1,
colour=title1)
```
### Create double line break with expression in legend title (and labels)
```{r, ggplot7, results='hide',eval=F}
ggplot() +
scale_color_manual(
expression(atop("text",
atop(textstyle(epsilon))))
)
ggplot() +
scale_color_manual(
name=expression(
atop("Productivity",
atop(textstyle(
(mg~C~L^{-1}~d^{-1}) # this is bracketed text
))))
)
```
### Adding text lables to plots
```{r, t1,eval=T}
require(ggplot2)
xx = sample(100, 100)
yy = rnorm(100)
df <- data.frame("X"=xx,"Y"=yy)
ggplot(df) +
geom_point(aes(xx,yy,size=5),colour=xx,show.legend = F) +
geom_text(aes(xx,yy,label=xx),check_overlap = T,size=yy+5) +
theme_classic()
# add bg label
ggplot() +
geom_line(aes(xx,yy,size=5),colour=xx,show.legend = F) +
geom_label(aes(xx,yy,label=xx),size=yy+5,color = yy +5, fill=xx) +
theme_classic()
```
Add text only to final point (plus other methods)
```{r, t2, eval=F}
require(directlabels)
df <- tibble("x" = sample(10,5),
"y" = sample(10,5),
"label" = LETTERS[1:5])
ggplot() +
geom_point(data = df, aes(x,y)) +
geom_dl(aes(label = label),
method = list(
dl.trans(x = x + 0.3, y = y + 0), # expand x/y axis to fit in labels
list(dl.combine("first.points","last.points")), cex = 0.5 # add labels to first and last points
)
) +
scale_x_continuous( ..., expand = c(0, 1.5))
```
### Calling data frame columns with weird formatting
```{r,gg9, eval = F}
# use ticks, not quotations
require(ggplot2)
df <- data.frame("X"=rnorm(1000),"Y col with spaces"=sample(1000,replace = T))
# incorrect y col, but doesn't throw error
ggplot(df, aes(X, "Y col with spaces")) +
geom_line()
# same issue even when matching col name
ggplot(df, aes(X, "Y.col.with.spaces")) +
geom_line()
# usable y col
ggplot(df, aes(X, `Y.col.with.spaces`)) +
geom_line()
```
### Use POSIX format
**Code Meaning**
%a Abbreviated weekday
%A Full weekday
%b Abbreviated month
%B Full month
%c Locale-specific date and time
%d Decimal date
%H Decimal hours (24 hour)
%I Decimal hours (12 hour)
%j Decimal day of the year
%m Decimal month
%M Decimal minute
%p Locale-specific AM/PM
%S Decimal second
%U Decimal week of the year (starting on Sunday)
%w Decimal Weekday (0=Sunday)
%W Decimal week of the year (starting on Monday)
%x Locale-specific Date
%X Locale-specific Time
%y 2-digit year
%Y 4-digit year
%z Offset from GMT
%Z Time zone (character)
```{r,gg10}
require(nycflights13);require(dplyr);require(ggplot2)
flights %>% str
flights$time_hour %>% class # already posix
flights_mod <- flights$time_hour %>% as.character() # convert posix to character
# turn into posix year month day hour minute second format
require(lubridate)
flights_mod <- flights_mod %>% ymd_hms()
flights_mod %>% class
# make new df with fewer data
df <- data.frame("Date"=flights_mod[1:100000],
"Delay"=flights$arr_delay[1:100000])
ggplot(df, aes(Delay,Date)) + geom_tile() +
scale_y_datetime(date_breaks = "1 month",
date_minor_breaks = "1 week", # optional
date_labels = "%B %Y" # full month and year
) +
theme_classic()
```
### Plotting multiple plots per window (with different plot size ratios) with `gridExtra`
```{r,mp1}
require(gridExtra)
nn <- 100 # create sample
p <- ggplot()+geom_point(aes(sample(nn,replace=T),rnorm(nn),size=runif(nn),color=rainbow(nn)),show.legend = F)+theme_classic()
# put plots into list
ggplot_list <- list(p,p,p,p)
# 3 plots above, 1 below
grid.arrange(
grobs = ggplot_list, # list with ggplots or grobs
widths = c(1, 1, 1),
layout_matrix = rbind(c(1, 2, 3),
c(4, 4, 4))
)
# 3 plots above with first plot 2 plots wide
grid.arrange(
grobs = ggplot_list, # list with ggplots or grobs
widths = c(2, 1, 1), # widths (2,1,1) of total plots for each row (3)
layout_matrix = rbind(c(1, 2, 3),
c(4, 4, 4))
)
# 2 plots below with third plot 3 plots wide
grid.arrange(
grobs = ggplot_list, # list with ggplots or grobs
widths = c(2, 1, 1),
layout_matrix = rbind(c(1, 2, NA),
c(3, 3, 4))
)
```
Arranging multiplot panels
```{r, mp2}
# https://patchwork.data-imaginist.com/articles/guides/assembly.html
# devtools::install_github("thomasp85/patchwork")
require(patchwork)
p1 <- ggplot(mtcars) +
geom_point(aes(mpg, disp, col = cyl), show.legend = F) +
ggtitle('Plot 1') + theme_classic()
p2 <- ggplot(mtcars) +
geom_point(aes(mpg, cyl, col = disp), show.legend = F) +
ggtitle('Plot 2') + theme_classic()
p3 <- p1; p4 <- p2
# 2 plots, 2 cols
p1 + p2
# multi rows
(p1 | p2 | p3) / p4 # 3 plots top, 1 bottom (2 rows)
p1 / (p2 | p3) # 1 plot top, 2 bottom (2 rows)
# 2 plots, 2 rows and 2 cols
wrap_plots(p1, p2, p3, p4)
# 3 plots, 2 cols
patch <- p1 + p2
p3 + patch
# non ggplot content eg. text
p1 + grid::textGrob('Some text')
p1 + gridExtra::tableGrob(mtcars[1:10, c('mpg', 'disp')])
# title, subs, and captions
patchwork <- (p1 + p2) / p3
patchwork + plot_annotation(
title = "ttl",
subtitle = "subttl",
caption = "caption"
)
```
### Setting legend to custom aes elements, e.g. color, shape, linetype
```{r,gg12,eval=T}
# set 'labs' arguments to same title as in 'scale_color_manual'
# legend values automatically matches arguments passed to colvec
# NB specifying the labels arg in scale_color_manual overrides labs
require(ggplot2)
snack_df <- data.frame(
"X"=sample(100,10,replace=F),
"Y"=sample(100,10,replace=F),
"Sum"=runif(10),
"Size"=rep(LETTERS[1:5],each=2)
)
colvec <- colorspace::sequential_hcl(length(unique(snack_df$Size)), "SunsetDark")
legend_ttl <- "This is your legend"
legend_pars <- unique(snack_df$Size) # not run
ggplot(snack_df,aes(X,Y)) +
geom_line(aes(group=Size,color=Size,linetype=Size),size=1) +
geom_point(aes(group=Size,color=Size,shape=Size),size=3) +
scale_color_manual(name=legend_ttl,
# labels = legend_pars, # this overrides labs
values = colvec) +
geom_text(aes(X,Y,
label=c(Size)
),
check_overlap = T,
size=5,vjust=-1,hjust=1.2) +
labs(title="Plot title",x="X",y="Y",
# ----- these are the legend key arguments
colour=legend_ttl,
fill=legend_ttl,
linetype=legend_ttl,
shape=legend_ttl) + # check shape
theme_classic()
```
### Pass variables as user arguments to plotting function
Option 1
```{r, gg13, eval =T}
# http://www.rebeccabarter.com/blog/2020-02-05_rstudio_conf/
require(tidyverse);require(dplyr)
midwest %>% head
plotMidwestTidy <- function(var1, var2) {
ggplot(midwest) +
geom_point(aes(
x = {{ var1 }}, y = {{ var2 }} # wrap vars in double curly braces
))
}
plotMidwestTidy(popdensity, poptotal) +
theme_bw()
```
Option 2
Can't use character class as user argument
```{r,gg13b, eval=F, echo = T}
require(ggplot2)
my_theme <- theme_classic()
colour_var <- "class"
facet_var <- "drv"
ggplot(mpg) +
geom_point(aes(displ, hwy, colour = colour_var)) +
facet_wrap(vars(facet_var)) + my_theme
```
Placing `.data` in front of your variables and wrapping them with double square braces '[[]]' solves this.
```{r, eval = T}
require(ggplot2)
my_theme <- theme_classic()
colour_var <- "class"
facet_var <- "drv"
ggplot(mpg) +
geom_point(aes(displ, hwy, colour = .data[[colour_var]])) +
facet_wrap(vars(.data[[facet_var]])) + my_theme +
ggtitle(paste0(colour_var, " vs ", facet_var))
```
### Use conditional statements in `ggplot` objects
```{r,gg14,eval=T}
require(ggplot2)
cond1 <- F
cond2 <- T
p <- ggplot(mtcars) +
geom_point(aes(mpg,hp,size=3),show.legend = F) +
theme_classic()
p <- p + if(cond1==T){ # execute condition 1 and add to plot
geom_line(aes(mpg,hp,size=3),color="red",show.legend = F)
}
p <- p + if(cond2==T){ # execute condition 2 and add to plot
geom_line(aes(mpg,hp,size=2),color="blue",show.legend = F)
}
p
```
Make calendar plot
```{r, gg15}
require(sugrrants)
require(nycflights13)
ff <- flights
ff <- ff %>% mutate(date = flights$time_hour %>% as.Date())
fdf <- frame_calendar(ff,
x = distance,
y = arr_delay,
date = date,
nrow = 4)
p <- ggplot(fdf) +
geom_line(aes(x = .distance,
y = .arr_delay,
group = date)) + theme_void()
p %>% prettify()
```
### Plot benchmark results
https://stackoverflow.com/questions/29803253/r-extracting-coordinates-from-spatialpolygonsdataframe
```{r, gg16, eval=F}
res <- microbenchmark(raster::geom(atf_sp),
ggplot2::fortify(atf_sp),
spbabel::sptable(atf_sp),
as.data.frame(as(as(atf_sp, "SpatialLinesDataFrame"),
"SpatialPointsDataFrame")))
ggplot2::autoplot(res)
```
### Flip, rotate, and reorder
Flip axis directions
```{r, f1, eval=F}
# rotate
print(p, vp=viewport(angle=-30))
p + coord_flip()
p + scale_y_reverse()
graphics.off()
```
Reorder data within variables to have custom plot order
```{r, f2, eval = F}
ggplot() +
geom_bar(data = df, aes(year, value,
fill = factor(var1, level = unique(var1)) # reorder to match order data is listed within variable
))
```
### Colour palettes
Match df column/variable to custom colour scale
```{r, col1, eval = F}
require(colorspace)
mycolors <- sequential_hcl(d %>% pull(var1) %>% n_distinct(), "Tofino")
names(mycolors) <- d$var1 %>% unique %>% factor %>% levels
custom_colors <- scale_colour_manual(name = "Title",
values = mycolors)
ggplot() +
geom_sf(data = d) +
custom_colors # add scale
require(colorspace)
require(scales)
# match sequential colpal as sequential values in df
colv <- colorRampPalette(colors = c(col_low ,col_high))
colpal <- colv(d$value %>% length)
d$colpal <- colpal
# match sequential colpal to unique values in df var
colpal <- sequential_hcl(d$value %>% length, "Sunset")
pal <- col_numeric(palette = colpal, domain = d$value)
d <- d %>% mutate("colpal" = pal(value))
# match custom palette colpal to unique values in df var
colv <- colorRampPalette(colors = c(col_low ,col_high))
colpal <- colv(d$value %>% length)
pal <- col_numeric(palette = colpal, domain = d$value)
d <- d %>% mutate("colpal" = pal(value))
# add optional highlight colours
d <- d %>% mutate_at("colpal", funs(case_when(
id_name == "name1" ~ "red",
TRUE ~ colpal
)))
# match colours based on df variable values
d <- d %>%
mutate("colpal" = case_when(
id_name %in% "name1" ~ "red",
TRUE ~ colpal # or e.g. "blue"
))
ggplot() +
geom_sf(data = d, aes(col = colpal)) +
scale_color_manual(values = d$colpal %>% unique) # then add manual colpal from df
```
Loop through different colpals and save plots to dir
```{r}
vars <- df$var1 %>% unique
colv <- c("Peach", "PinkYl", "Burg")
for(i in seq_along(vars)){
df <- df %>% filter(var1 == vars[i])
xlab <- "Month"
ylab <- "Day"
nn <- df %>% pull(var2) %>% n_distinct()
colpal <- c(sequential_hcl(nn,colv[i]) %>% .[nn],sequential_hcl(nn,colv[i]) %>% .[1]) # set col gradient
ggplot() +
geom_tile(data = df, aes(v1,v2,fill = ar2)) +
scale_fill_gradient(low = colpal[1], high = colpal[2], guide = "colourbar",na.value = "transparent") # create custom gradient
ggsave(here::here("plot",var1[i],"_activity.png"),device = "png")
}
```
Create gradient colour for area plot (AUC)
<!-- https://datacornering.com/how-to-create-gradient-shade-under-the-line-chart-in-r/ -->
```{r, col4, eval = F}
library(minisvg)
library(devout)
library(devoutsvg)
library(poissoned)
library(svgpatternsimple)
require(ggplot2)
require(ggdark)
# create gradient
gradient_pattern <- create_pattern_gradient(
id = "p1",
angle = 90,
colour1 = "#1A1A1A",
colour2 = "#63CB99",
alpha = 0.8
)
gradient_pattern$show()
# save gradient as svg
my_pattern_list <- list(`#000001` = list(fill = gradient_pattern))
svgout(
filename = "line-chart-with-gradient-shade.svg",
pattern_list = my_pattern_list,
width = 10,
height = 5
)
# plot
ggplot(btc, aes(x = Date, y = Price)) +
geom_line(color = "#63CB99",
size = 0.4,
alpha = 0.9) +
geom_area(alpha = 0.3,
fill = "#000001",
color = alpha(0.1)) +
ggtitle("BTC price, USD") +
scale_y_continuous(labels = scales::comma)
```
Glow effect for line plot
<!-- https://datacornering.com/how-to-add-glow-effect-in-r-plot/ -->
```{r, col5, eval = F}
require(ggshadow)
require(ggplot2)
require(ggthemes)
ggplot(btc, aes(x = Date, y = Price)) +
geom_glowline(color = "gold", shadowcolour = "orange") +
theme_solarized_2(light = FALSE) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
```
### Images
Fill plot view with image
```{r, gg19, eval=F}
require(png)
require(jpeg)
imgr <- img %>% readPNG()
ggplot() +
annotation_raster(imgr, -Inf, Inf, -Inf, Inf)
```
Fill geom with patterns/images
https://coolbutuseless.github.io/package/ggpattern/index.html
```{r, gg20, eval=F}
```
Read in png, recolor, write as svg, and append to df
```{r, eval =F}
here::here("img",paste0(ifh,".png")) %>%
image_read(strip = T) %>%
# image_scale(c(100,100)) %>%
image_fill("transparent") %>%
image_colorize(color = colv_hi,opacity = 70) %>% # recolor img
image_write(here::here("img",paste0(ifh,"2.png")) ,format = "png", depth=NULL)
# append to df
df$img <- here::here("img",paste0(ifh,"2.png"))
```
### Create custom geom
```{r, gg21, eval=F}
library(ggplot2)
x <- 1:100
my_geom_y <- function(yy, colour = "black"){
list(
geom_line(aes(y= yy),
col = colour),
data = data.frame(x, yy),
geom_point(aes(y = yy),
col = colour,
data = data.frame(x, yy))
)
}
ggplot(aes(x)) +
my_geom_y(x, "red") +
my_geom_y(dlnorm(x), "blue") +
my_geom_y((x^1.1), "black") +
my_geom_y(x/2, "yellow")
```
Highlight variables in plot
```{r, gg22, eval=T}
library(ggplot2)
library(gghighlight)
ggplot(mpg, aes(x = cty, y = hwy)) +
geom_point(color = "red",
size=2) +
gghighlight(class == "midsize")
```
Set inner circle width for circular barplot
```{r, gg23, eval=F}
ylim <- 40
ggplot() +
geom_histogram(data = d,
aes(xx,id,fill = yy), size = 0, position = "stack", stat = "identity", show.legend = F) +
scale_fill_manual(values = adjustcolor(colv,1),aesthetics = c("col","fill")) +
facet_wrap(~zz) +
theme_classic() +
coord_polar(start = 0.25) +
scale_x_continuous(breaks = 1:12, labels = xtick) +
# option 1
scale_y_continuous(expand = c(0.2,0)) +
# option 2
scale_y_continuous(limits = c(-10,NA), breaks = seq(0,ylim,ylim/4), labels = seq(0,ylim,ylim/4))
```
Add histogram dist to boxplots (from Eli data)
```{r, gg24, eval = F}
limits <- d$yy %>% unique
colv <- colorspace::sequential_hcl(limits, "Blues")
require(ggdist)
ggplot(data = d, aes(x = xx, y = yy,
col = yy, fill = yy
)) +
geom_boxplot(outlier.color = NA) + # boxplot
geom_jitter(height = 0.2) + # jitter points
ggdist::stat_dots(binwidth = 0.2, # opt 1: dot plot
side = "left",
justification = 1.1,
col = NA) +
ggdist::stat_halfeye(slab_type = "pdf",
limits = c(1, NA), # rm data < 1
adjust = 0.5, # opt 2: point dist
width = 0.5,
.width = 0, # decrease iqr line width
justification = -0.5, # move dist above box
point_colour = NA) +
scale_y_discrete(limits=limits) + # reorder xaxis
scale_colour_manual(values = colv,aesthetics = "col", limits = limits, labels = limits) + # keep solid col for boxplot
scale_fill_manual(values = adjustcolor(colv,0.7), aesthetics = "fill",limits = limits, labels = limits) + # add alpha to boxplot fill
theme_classic()
```
Maintain order of variables in df when plotting
```{r, c1, eval = F}
limits <- df$var1 %>% pull
df %>% ggplot() +
geom_col(aes(x,y)) +
scale_x_discrete(limits = limits)
# option 2 (works for factor variables with barplot)
require(forcats)
df %>% ggplot() +
geom_bar(aes(fct_infreq(y)))
# reverse variable order
df %>% ggplot() +
geom_bar(aes(fct_rev(y)))
```
### Insert plot inset within main plot
```{r, inset1, eval = F}
### opt 1
# first create and save plot inset to local dir
plot_inset <- ggplot() +
geom_point(data = inset_data)
#
ggsave("plot_inset.png",plot_inset)
plot_inset <- "plot_inset.png" %>% readPNG() # read in saved plot
# main plot
ggplot() +
geom_sf(data = data) +
# add plot inset
annotation_raster(plot_inset,xmin = xmin, xmax = xmax, ymin = ymin ,ymax = ymax) +
# themes
theme_nothing()
### opt 2
ggdraw() +
draw_plot(main1, 0, 0, 1, 1) +
draw_plot(legend1, 0.15, 0.7, 0.18, 0.18)
```
### Legends
Custom shape for legend
```{r, gg25, eval=T}
# ?draw_key # see available glyphs
require(ggplot2)
require(dplyr)
require(colorspace)
glyph <- "pointrange"
df <- data.frame(xx = rep(1:5,each=3),
yy = 1:15,
group = rep(c("A","B","C"),each=5))
ggplot(data=df,aes(xx,yy,col = group, fill = group)) +
geom_line(key_glyph = glyph) + # set shape for legend
scale_fill_discrete_sequential(name = paste0(glyph, " legend"), "Reds", aesthetics = "col") +
theme_bw() +
guides(col = guide_legend(
override.aes = list(size = 1) # set custom legend size
))
```
Fine tune legend features e.g. text, padding, vertical/horizontal spacing
<!-- https://stackoverflow.com/questions/11366964/is-there-a-way-to-change-the-spacing-between-legend-items-in-ggplot2 -->
```{r, gg26, eval=T}
df <- data.frame(xx = sample(100, 100),
yy = rnorm(100))
ggplot(data=df,aes(xx,yy,col = yy, fill = yy)) +
geom_point() +
theme_classic() +
theme(legend.position = "bottom") +
# legend guide for colourbar
guides(fill = guide_colorbar(title = "Continuous",
label.position ="left")) +
# legend guid for categorical
guides(fill = guide_legend(title = "Categorical",
label.position ="right"))
```
Toggle legend when using `scale_*_()` functions
```{r, gg27, eval=F}
ggplot() +
geom_point(data = df, aes(fill = var1)) +
scale_fill_manual(values = colpal, aesthetics = "fill", guide = F) # T/F to toggle show legend
```
Customise attributes of two separate legends e.g. size and colour bar
```{r, legend4, eval = F}
# set colourbar for var1 (color gradient) but also change colour/fill of legend for var2 (size)
ggplot() +
geom_sf(data = df,aes(col=var1,fill=var1,size=var2)) +
# var 1 attributes (colour/fill gradient)
scale_fill_gradientn(name = title1, colours = adjustcolor(colpal,0.5),aesthetics = c("col","fill"), na.value = "#EFEFEF") +
# var 2 attributes (size)
guides(size = guide_legend(title = title2,
override.aes = list(fill = col_var2, alpha = 0.5, col = col_var2) # change colour for size legend (var2)
))
```
Change legend font, size, bg, opacity, and position
```{r,legend5, eval =F}
opac <- 0.5
theme(legend.position=c(0.2,0.2), #xy from bottom left
legend.key.size = unit(0.5, "cm"), # size
legend.background = element_rect(fill=alpha(fg, opac)), # legend background
legend.title = element_text(family = family,colour = col_font),
legend.text = element_text(family = family,colour = col_font)
)
```
Biscale legend
<!-- https://github.com/richardvogg/30DayMapChallenge21/blob/master/day17_land/day17_land.R -->
```{r, legend6, eval = F}
require(biscale)
data <- bi_class(df, sf1, sf2, dim = 3)
legend <- bi_legend(pal = "GrPink",
dim = 3,
xlab = "More sf1",
ylab = "More sf2",
size = 12)
map <- ggplot() +
geom_tile(data = data , aes(x = x, y = y, fill = bi_class), show.legend = F) +
bi_scale_fill(pal = "GrPink", dim = 3) + # create biscale
bi_theme()
# combine legend and map
ggdraw() +
draw_plot(map, 0, 0, 1, 1) +
draw_plot(legend, 0.15, 0.7, 0.18, 0.18)
```
Blank theme with full legend
```{r, legend7}
require(ggthemes)
p1 + theme_map() +
theme(legend.background = element_rect(fill = "transparent"))
```
Setting custom legend position for wrapped/stacked plots
```{r, legend8}
require(patchwork)
# can specify legend position using theme(legend.position=...)
wrap_plots(p,p1,p2, ncol = 2,
guides = "collect" #"keep" "auto"
)
```
Combine df aes elements (e.g. colour and size) into one legend
```{r, legend9}
require(dplyr)
require(ggplot2)
require(colorspace)
df <- tibble("x" = 1:10,
"y" = 11:20,