-
Notifications
You must be signed in to change notification settings - Fork 10
/
slide_ggplot2.Rmd
1060 lines (806 loc) · 23.4 KB
/
slide_ggplot2.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: "Visualisation with `ggplot2`"
subtitle: "R Foundations for Life Scientists"
author: "Lokesh Mano (Roy Francis)"
keywords: r, rmarkdown, ggplot, graphics
output:
xaringan::moon_reader:
encoding: 'UTF-8'
self_contained: false
chakra: 'assets/remark-latest.min.js'
css: 'assets/slide.css'
lib_dir: libs
nature:
ratio: '4:3'
highlightLanguage: r
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
slideNumberFormat: "%current%/%total%"
---
exclude: true
count: false
```{r,echo=FALSE,child="assets/header-slide.Rmd"}
```
<!-- ----------------- Only edit title & author above this ----------------- -->
```{r,echo=FALSE,message=FALSE,warning=FALSE}
# load packages
library(dplyr)
library(tidyr)
library(ggplot2)
library(patchwork)
library(tibble)
#colors
rv_col_dark <- "#125687"
rv_col_light <- "#e7eef3"
```
# Contents
* [Why `ggplot2`?](#intro)
* [Grammar of Graphics](#gog)
* [Data](#data-iris)
* [Geoms](#geom)
* [Aesthetics](#aes)
* [Scales](#scales-discrete-colour)
* [Facets](#facet-wrap)
* [Coordinates](#coordinate)
* [Theme](#theme)
* [Position](#position)
* [Saving Plots](#save)
* [Combining Plots](#comb)
* [Interactive Plots](#interactive)
* [Extensions](#extension)
---
name: intro
class: spaced
# Why `ggplot2`?
* Consistent code
* Flexible
* Automatic legends, colors etc
* Save plot objects
* Themes for reusing styles
* Numerous add-ons/extensions
* Nearly complete graphing solution
--
Not suitable for:
* 3D graphics
???
Why can't we just do everything is base plot? Of course, we could, but it's easier, consistent and more structured using `ggplot2`. There is bit of a learning curve, but once the code syntax and graphic building logic is clear, it becomes easy to plot a large variety of graphs.
---
name: gvb1
# `ggplot2` vs Base Graphics
.pull-left-50[
```{r,fig.height=4.5,fig.width=4}
hist(iris$Sepal.Length)
```
]
.pull-right-50[
```{r,fig.height=4,fig.width=4}
library(ggplot2)
ggplot(iris,aes(x=Sepal.Length))+
geom_histogram(bins=8)
```
]
???
For simple graphs, the base plot seem to take minimal coding effort compared to a ggplot graph.
---
name: gvb2
# `ggplot2` vs Base Graphics
.pull-left-50[
```{r,fig.height=4.5,fig.width=4}
plot(iris$Petal.Length,iris$Petal.Width,
col=c("red","green","blue")[iris$Species],
pch=c(0,1,2)[iris$Species])
legend(x=1,y=2.5,
legend=c("setosa","versicolor","virginica"),
pch=c(0,1,2),col=c("red","green","blue"))
```
]
.pull-right-50[
```{r,fig.height=4,fig.width=5}
ggplot(iris,aes(Petal.Length,Sepal.Length,color=Species))+
geom_point()
```
]
???
For anything beyond extremely basic plots, base plotting quickly become complex. More importantly, base plots do not have consistency in it's functions or plotting strategy.
---
name: gog
class: spaced
# Grammar Of Graphics
.pull-left-30[
![](data/slide_ggplot2/gog.jpg)
![](data/slide_ggplot2/gog.png)
]
--
.pull-right-70[
* **Data**: Input data
* **Geom**: A geometry representing data. Points, Lines etc
* **Aesthetic**: Visual characteristics of the geometry. Size, Color, Shape etc
* **Scale**: How visual characteristics are converted to display values
* **Statistics**: Statistical transformations. Counts, Means etc
* **Coordinates**: Numeric system to determine position of geometry. Cartesian, Polar etc
* **Facets**: Split data into subsets
]
???
`ggplot` was created by Hadley Wickham in 2005 as an implementation of Leland Wilkinson's book Grammar of Graphics.
Different graphs have always been considered as independent entities and also labelled differently such as barplots, scatterplots, boxplots etc. Each graph has it's own function and plotting strategy.
Grammar of graphics (GOG) tries to unify all graphs under a common umbrella. GOG brings the idea that graphs are made up of discrete components which can be mixed and matched to create any plot. This creates a consistent underlying framework to graphing.
---
name: syntax
# Building A Graph: Syntax
![](data/slide_ggplot2/syntax.png)
---
name: build-1
# Building A Graph
.pull-left-40[
```{r,fig.height=3.5,fig.width=3.5,eval=FALSE}
ggplot(iris)
```
]
.pull-right-50[
```{r,fig.height=3.5,fig.width=3.5,echo=FALSE}
data(iris)
ggplot(iris)
```
]
---
name: build-2
# Building A Graph
.pull-left-40[
```{r,fig.height=3.5,fig.width=3.5,eval=FALSE}
ggplot(iris,aes(x=Sepal.Length,
y=Sepal.Width))
```
]
.pull-right-60[
```{r,fig.height=3.5,fig.width=3.5,echo=FALSE}
ggplot(iris,aes(x=Sepal.Length,
y=Sepal.Width))
```
]
---
name: build-3
# Building A Graph
.pull-left-40[
```{r,fig.height=3.5,fig.width=3.5,eval=FALSE}
ggplot(iris,aes(x=Sepal.Length,
y=Sepal.Width))+
geom_point()
```
]
.pull-right-60[
```{r,fig.height=3.5,fig.width=3.5,echo=FALSE}
ggplot(iris,aes(x=Sepal.Length,
y=Sepal.Width))+
geom_point()
```
]
---
name: build-4
# Building A Graph
.pull-left-40[
```{r,fig.height=3.5,fig.width=3.5,eval=FALSE}
ggplot(iris,aes(x=Sepal.Length,
y=Sepal.Width,
colour=Species))+
geom_point()
```
]
.pull-right-60[
```{r,fig.height=3.5,fig.width=3.5,echo=FALSE}
ggplot(iris,aes(x=Sepal.Length,
y=Sepal.Width,
colour=Species))+
geom_point()
```
]
---
name: data-iris
# Data • `iris`
* Input data is always an R `data.frame` object
```{r,echo=FALSE}
iris %>%
head(n=3) %>%
kable("html",escape=F,align="c")
```
```{r}
str(iris)
```
???
It's a good idea to use `str()` to check the input dataframe to make sure that numbers are actually numbers and not characters, for example. Verify that factors are correctly assigned.
---
name: data-diamonds
# Data • `diamonds`
```{r,echo=FALSE}
head(diamonds,n=3) %>%
na.omit() %>%
kable("html",escape=F,align="c")
```
```{r}
str(diamonds)
```
???
R `data.frame` is a tabular format with rows and columns just like a spreadsheet. All items in a row or a column must be available or missing values filled in as NAs.
---
name: data-format
# Data • Format
--
- Wide format
```{r, echo=FALSE}
gc <- read.table("data/slide_ggplot2/counts_raw.txt", header = T, row.names = 1, sep = "\t")
kable(gc[c(1:6),c(1:4)]) %>%
kable_styling(bootstrap_options = "striped", full_width = F) %>%
row_spec(1:6, color = "orange") %>%
column_spec(1, color = "red") %>%
row_spec(0, bold = T, color = "blue")
```
--
* familiarity
* conveniency
* you see more data
---
name: data-format-2
# Data • Format
- Long format
--
```{r echo=FALSE}
md <- read.table("data/slide_ggplot2/metadata.csv", header = T, sep = ";")
samples <- colnames(gc[,c(1:4)])
gc[c(1:6),c(1:4)] %>%
rownames_to_column(var = "Gene") %>%
gather(Sample_ID, count, -Gene) %>%
select(Sample_ID, everything()) %>%
head(6) %>%
kable() %>%
kable_styling("striped", full_width = F) %>%
column_spec(1, color = "blue") %>%
column_spec(2, color = "red")%>%
column_spec(3, color = "orange")
```
--
```{r echo=FALSE}
md <- read.table("data/slide_ggplot2/metadata.csv", header = T, sep = ";")
samples <- colnames(gc[,c(1:4)])
gc[c(1:6),c(1:4)] %>%
rownames_to_column(var = "Gene") %>%
gather(Sample_ID, count, -Gene) %>%
full_join(md[c(1:4),], by = "Sample_ID") %>%
select(Sample_ID, everything()) %>%
select(-c(Gene,count), c(Gene,count)) %>%
head(6) %>%
kable() %>%
kable_styling("striped", full_width = F) %>%
column_spec(1:5, color = "blue") %>%
column_spec(6, color = "red")%>%
column_spec(7, color = "orange")
```
---
name: data-format-3
# Data • Format
- Long format
```{r echo=FALSE}
md <- read.table("data/slide_ggplot2/metadata.csv", header = T, sep = ";")
samples <- colnames(gc[,c(1:4)])
gc[c(1:6),c(1:4)] %>%
rownames_to_column(var = "Gene") %>%
gather(Sample_ID, count, -Gene) %>%
full_join(md[c(1:4),], by = "Sample_ID") %>%
select(Sample_ID, everything()) %>%
select(-c(Gene,count), c(Gene,count)) %>%
head(6) %>%
kable() %>%
kable_styling("striped", full_width = F) %>%
column_spec(1:5, color = "blue") %>%
column_spec(6, color = "red")%>%
column_spec(7, color = "orange")
```
--
* easier to add data to the existing
* Most databases store and maintain in long-formats due to its efficiency
* R tools **like ggplot** require data in long format.
* Functions available to change between data-formats
* `melt()` from **reshape2**
* `gather()` from **tidyverse**
---
name: geom
# Geoms
![geoms](data/slide_ggplot2/geoms.png)
--
```{r,eval=FALSE}
p <- ggplot(iris)
# scatterplot
p+geom_point(aes(x=Sepal.Length,y=Sepal.Width))
# barplot
p+geom_bar(aes(x=Sepal.Length))
# boxplot
p+geom_boxplot(aes(x=Species,y=Sepal.Width))
# search
help.search("^geom_",package="ggplot2")
```
???
Geoms are the geometric components of a graph such as points, lines etc used to represent data. The same data can be visually represented in different geoms. For example, points or bars. Mandatory input requirements change depending on geoms.
---
name: aes
# Aesthetics
* Aesthetic mapping vs aesthetic parameter
.pull-left-50[
```{r,fig.height=4,fig.width=5.5}
ggplot(iris)+
geom_point(aes(x=Sepal.Length,
y=Sepal.Width,
size=Petal.Length,
alpha=Petal.Width,
shape=Species,
color=Species))
```
]
.pull-left-50[
```{r,fig.height=4,fig.width=4}
ggplot(iris)+
geom_point(aes(x=Sepal.Length,
y=Sepal.Width),
size=2,
alpha=0.8,
shape=15,
color="steelblue")
```
]
???
Aesthetics are used to assign values to geometries. For example, a set of points can be a fixed size or can be different colors or sizes denoting a variable.
This would be an incorrect way to do it.
```
ggplot(iris)+
geom_point(aes(x=Sepal.Length,y=Sepal.Width,size=2)
```
---
name: aes-2
# Aesthetics
```{r,echo=TRUE,fig.height=4,fig.width=8}
x1 <- ggplot(iris) +
geom_point(aes(x=Sepal.Length,y=Sepal.Width))+
stat_smooth(aes(x=Sepal.Length,y=Sepal.Width))
x2 <- ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point() + geom_smooth()
x1|x2
```
???
If the same aesthetics are used in multiple geoms, they can be moved to `ggplot()`.
---
name: multiple-geom
# Multiple Geoms
```{r,fig.height=4.8,fig.width=9}
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point()+
geom_line()+
geom_smooth()+
geom_rug()+
geom_step()+
geom_text(data=subset(iris,iris$Species=="setosa"),aes(label=Species))
```
???
Multiple geoms can be plotted one after the other. The order in which items are specified in the command dictates the plotting order on the actual plot.
In this case, the points appear over the lines.
```
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point()+
geom_line()+
```
while here the lines appear above the points.
```
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_line()+
geom_point()+
```
Each geom takes input from `ggplot()` inputs. If extra input is required to a geom, it can be specified additionally inside `aes()`.
`data` can be changed if needed for specific geoms.
---
name: scales-discrete-color
# Scales • Discrete Colors
* scales: position, color, fill, size, shape, alpha, linetype
* syntax: `scale_<aesthetic>_<type>`
<img src="data/slide_ggplot2/scales.png" alt="scales-syntax" style="width:50%;">
--
.pull-left-50[
```{r,fig.height=2.7,fig.width=4}
p <- ggplot(iris)+geom_point(aes(x=Sepal.Length,
y=Sepal.Width,color=Species))
p
```
]
--
.pull-right-50[
```{r,fig.height=2.7,fig.width=4}
p + scale_color_manual(
name="Manual",
values=c("#5BC0EB","#FDE74C","#9BC53D"))
```
]
???
Scales are used to control the aesthetics. For example the aesthetic color is mapped to a variable `x`. The palette of colors used, the mapping of which color to which value, the upper and lower limit of the data and colors etc is controlled by scales.
---
name: scales-continuous-color
# Scales • Continuous Colors
* In RStudio, type `scale_`, then press **TAB**
--
.pull-left-50[
```{r,fig.height=4,fig.width=5}
p <- ggplot(iris)+
geom_point(aes(x=Sepal.Length,
y=Sepal.Width,
shape=Species,color=Petal.Length))
p
```
]
--
.pull-right-50[
```{r,fig.height=4,fig.width=5}
p +
scale_color_gradient(name="Pet Len",
breaks=range(iris$Petal.Length),
labels=c("Min","Max"),
low="black",high="red")
```
]
???
Continuous colours can be changed using `scale_color_gradient()` for two colour gradient. Any number of breaks and colours can be specified using `scale_color_gradientn()`.
---
name: scales-shape
# Scales • Shape
.pull-left-50[
```{r,fig.height=4,fig.width=5}
p <- ggplot(iris)+
geom_point(aes(x=Sepal.Length,
y=Sepal.Width,
shape=Species,color=Species))
p
```
]
--
.pull-right-50[
```{r,fig.height=4,fig.width=5}
p +
scale_color_manual(name="New",
values=c("blue","green","red"))+
scale_shape_manual(name="Bla",values=c(0,1,2))
```
]
???
Shape scale can be adjusted using `scale_shape_manual()`. Multiple mappings for the same variable groups legends.
---
name: scales-axis
# Scales • Axes
* scales: x, y
* syntax: `scale_<axis>_<type>`
* arguments: name, limits, breaks, labels
--
.pull-left-50[
```{r,fig.height=4,fig.width=5}
p <- ggplot(iris)+
geom_point(aes(x=Sepal.Length,
y=Sepal.Width))
p
```
]
--
.pull-right-50[
```{r,fig.height=4,fig.width=5}
p + scale_color_manual(name="New",
values=c("blue","green","red"))+
scale_x_continuous(name="Sepal Length",
breaks=seq(1,8),limits=c(3,5))
```
]
???
The x and y axes are also controlled by scales. The axis break points, the break point text and limits are controlled through scales.
When setting limits using `scale_`, the data outside the limits are dropped. Limits can also be set using `lims(x=c(3.5))` or `xlim(c(3,5))`. When mapping, `coord_map()` or `coord_cartesian()` is recommended for setting limits.
---
name: facet-wrap
# Facets • `facet_wrap`
* Split to subplots based on variable(s)
* Facetting in one dimension
--
.pull-left-50[
```{r,fig.height=4.5,fig.width=5}
p <- ggplot(iris)+
geom_point(aes(x=Sepal.Length,
y=Sepal.Width,
color=Species))
p
```
]
--
.pull-right-50[
```{r,fig.height=2.2,fig.width=4.5}
p + facet_wrap(~Species)
```
```{r,fig.height=2.4,fig.width=4.5}
p + facet_wrap(~Species,nrow=3)
```
]
???
`facet_wrap` is used to split a plot into subplots based on the categories in one or more variables.
---
name: facet-grid
# Facets • `facet_grid`
* Facetting in two dimensions
.pull-left-50[
```{r,fig.height=3.5,fig.width=5}
p <- diamonds %>%
ggplot(aes(carat,price))+
geom_point()
p + facet_grid(~cut+clarity)
```
]
--
.pull-left-50[
```{r,fig.height=4.2,fig.width=5.2}
p + facet_grid(cut~clarity)
```
]
???
`facet_grid` is also used to split a plot into subplots based on the categories in one or more variables. `facet_grid` can be used to create a matrix-like grid of two variables.
---
name: coordinate
# Coordinate Systems
![](data/slide_ggplot2/coordinate.png)
* `coord_cartesian(xlim=c(2,8))` for zooming in
* `coord_map` for controlling limits on maps
* `coord_polar`
.pull-left-50[
```{r,fig.height=3.4,fig.width=4}
p <- ggplot(iris,aes(x="",y=Petal.Length,fill=Species))+
geom_bar(stat="identity")
p
```
]
???
The coordinate system defines the surface used to represent numbers. Most plots use the cartesian coordinate sytem. Pie charts for example, is a polar coordinate projection of a cartesian barplot. Maps for example can have numerous coordinate systems called map projections. For example; UTM coordinates.
--
.pull-right-50[
```{r,fig.height=3.9,fig.width=4.4}
p+coord_polar("y",start=0)
```
]
---
name: theme
# Theme
* Modify non-data plot elements/appearance
* Axis labels, panel colors, legend appearance etc
* Save a particular appearance for reuse
* `?theme`
--
.pull-left-50[
```{r,fig.height=4,fig.width=4}
ggplot(iris,aes(Petal.Length))+
geom_histogram()+
facet_wrap(~Species,nrow=2)+
theme_grey()
```
]
--
.pull-right-50[
```{r,fig.height=4,fig.width=4}
ggplot(iris,aes(Petal.Length))+
geom_histogram()+
facet_wrap(~Species,nrow=2)+
theme_bw()
```
]
???
Themes allow to modify all non-data related components of the plot. This is the visual appearance of the plot. Examples include the axes line thickness, the background color or font family.
---
name: theme-legend
# Theme • Legend
```{r,fig.height=3,fig.width=4}
p <- ggplot(iris)+
geom_point(aes(x=Sepal.Length,
y=Sepal.Width,
color=Species))
```
.pull-left-50[
```{r,fig.height=4.3,fig.width=4.3}
p + theme(legend.position="top")
```
]
.pull-right-50[
```{r,fig.height=4.3,fig.width=4.3}
p + theme(legend.position="bottom")
```
]
---
name: theme-text
# Theme • Text
```{r,eval=FALSE}
element_text(family=NULL,face=NULL,color=NULL,size=NULL,hjust=NULL,
vjust=NULL, angle=NULL,lineheight=NULL,margin = NULL)
```
```{r,echo=FALSE}
p <- diamonds %>%
filter(cut=="Fair"|cut=="Good",color=="D"|color=="E") %>%
droplevels() %>%
ggplot(aes(carat,price,alpha=color,shape=cut))+
geom_point()+
labs(title="Title",subtitle="subtitle")+
facet_grid(cut~color)
```
```{r}
p <- p + theme(
axis.title=element_text(color="#e41a1c"),
axis.text=element_text(color="#377eb8"),
plot.title=element_text(color="#4daf4a"),
plot.subtitle=element_text(color="#984ea3"),
legend.text=element_text(color="#ff7f00"),
legend.title=element_text(color="#ffff33"),
strip.text=element_text(color="#a65628")
)
```
```{r,fig.height=4,fig.width=10,echo=FALSE}
dfr <- data.frame(value=rep(1,7),label=c("axis.title","axis.text","plot.title","plot.subtitle","legend.text","legend.title","strip.text"),stringsAsFactors=FALSE) %>%
mutate(label=factor(label,levels=c("axis.title","axis.text","plot.title","plot.subtitle","legend.text","legend.title","strip.text")))
q <- ggplot(dfr,aes(x=label,y=value,fill=label))+
geom_bar(stat="identity")+
labs(x="",y="")+
coord_flip()+
scale_fill_manual(values=c("#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628"))+
theme_minimal(base_size=20)+
theme(
legend.position="none",
axis.text.x=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank())
p|q
```
---
name: theme-rect
# Theme • Rect
```{r,eval=FALSE}
element_rect(fill=NULL,color=NULL,size=NULL,linetype=NULL)
```
```{r,echo=FALSE}
p <- diamonds %>%
filter(cut=="Fair"|cut=="Good",color=="D"|color=="E") %>%
droplevels() %>%
ggplot(aes(carat,price,alpha=color,shape=cut))+
geom_point()+
labs(title="Title",subtitle="subtitle")+
facet_grid(cut~color)
```
```{r}
p <- p + theme(
plot.background=element_rect(fill="#b3e2cd"),
panel.background=element_rect(fill="#fdcdac"),
panel.border=element_rect(fill=NA,color="#cbd5e8",size=3),
legend.background=element_rect(fill="#f4cae4"),
legend.box.background=element_rect(fill="#e6f5c9"),
strip.background=element_rect(fill="#fff2ae")
)
```
```{r,fig.height=3.8,fig.width=10,echo=FALSE}
dfr <- data.frame(value=rep(1,6),label=c("plot.background","panel.background","panel.border","legend.background","legend.box.background","strip.background"),stringsAsFactors=FALSE) %>%
mutate(label=factor(label,levels=c("plot.background","panel.background","panel.border","legend.background","legend.box.background","strip.background")))
q <- ggplot(dfr,aes(x=label,y=value,fill=label))+
geom_bar(stat="identity")+
labs(x="",y="")+
coord_flip()+
scale_fill_manual(values=c("#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae"))+
theme_minimal(base_size=20)+
theme(
legend.position="none",
axis.text.x=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank())
p|q
```
---
name: theme-save
# Theme • Reuse
```{r,echo=FALSE}
p <- diamonds %>%
filter(cut=="Fair"|cut=="Good"|cut=="Very Good") %>%
droplevels() %>%
ggplot(aes(carat,price,color=cut))+
geom_point()
```
```{r,echo=TRUE}
newtheme <- theme_bw() + theme(
axis.ticks=element_blank(),
panel.background=element_rect(fill="white"),
panel.grid.minor=element_blank(),
panel.grid.major.x=element_blank(),
panel.grid.major.y=element_line(size=0.3,color="grey90"),
panel.border=element_blank(),
legend.position="top",
legend.justification="right"
)
```
.pull-left-50[
```{r,echo=TRUE,fig.height=3.5,fig.width=5}
p
```
]
.pull-right-50[
```{r,fig.height=3.3,fig.width=4.5}
p + newtheme
```
]
---
name: position
# Position
```{r,echo=FALSE}
USArrests %>% head(n=3)
```
```{r}
us <- USArrests %>% mutate(state=rownames(.)) %>% slice(1:4) %>%
gather(key=type,value=value,-state)
p <- ggplot(us,aes(x=state,y=value,fill=type))
```
--
.pull-left-50[
```{r,fig.height=3.3,fig.width=4.5}
p + geom_bar(stat="identity",position="stack")
```
]
--
.pull-right-50[
```{r,fig.height=3.3,fig.width=4.5}
p + geom_bar(stat="identity",position="dodge")
```
]
---
name: save
# Saving plots
```{r,eval=FALSE}
p <- ggplot(iris,aes(Petal.Length,Sepal.Length,color=Species))+
geom_point()
```
* `ggplot2` plots can be saved just like base plots
```{r,eval=FALSE}
png("plot.png",height=5,width=7,units="cm",res=200)
print(p)
dev.off()
```