-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path08-general.Rmd
3610 lines (2653 loc) · 119 KB
/
08-general.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
# General Knowledge {#general}
---
## `ggplot2`
---
<center>
![](https://www.r-graph-gallery.com/img/other/ggplot2Hex.jpg)
</center>
<br>
`ggplot2` is a `R` package dedicated to data visualization. It can greatly improve the quality and aesthetics of your graphics, and will make you much more efficient in creating them.
`ggplot2` allows to build almost any type of chart. The R graph
gallery focuses on it so almost every section there starts with `ggplot2` examples.
This page is dedicated to general `ggplot2` tips that you can apply to any chart, like customizing a title, adding annotation, or using faceting. If you're new to `ggplot2`, a good starting point is probably this [online course](https://www.datacamp.com/?tap_a=5644-dce66f&tap_s=230804-f65650).
### Add Text Labels with `ggplot2`
This document is dedicated to text annotation with `ggplot2`. It provides several examples with reproducible code showing how to use function like `geom_label` and `geom_text`.
#### Adding Text with `geom_text()`
This example demonstrates how to use `geom_text()` to add text as markers. It works pretty much the same as `geom_point()`, but add text instead of circles. A few arguments must be provided:
* `label`: what text you want to display.
* `nudge_x` and `nudge_y`: shifts the text along X and Y axis.
* `check_overlap` tries to avoid text overlap. Note that a package called `ggrepel` extends this concept further.
```r
# library
library(ggplot2)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# 1/ add text with geom_text, use nudge to nudge the text
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_text(
label=rownames(data),
nudge_x = 0.25, nudge_y = 0.25,
check_overlap = T
)
```
<center>
![](https://www.r-graph-gallery.com/275-add-text-labels-with-ggplot2_files/figure-html/thecode-1.png){width=75%}
</center>
### Add Labels with `geom_label()`
`geom_label()` works pretty much the same way as `geom_text()`. However, text is wrapped in a rectangle that you can customize (see next example).
```r
# library
library(ggplot2)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# 1/ add text with geom_text, use nudge to nudge the text
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_label(
label=rownames(data),
nudge_x = 0.25, nudge_y = 0.25,
check_overlap = T
)
```
<center>
![](https://www.r-graph-gallery.com/275-add-text-labels-with-ggplot2_files/figure-html/thecode2-1.png){width=75%}
</center>
### Add One Text Label Only
Of course, you don't have to label all dots on the chart. You can also add a piece of text on a specific position. Since we're here, note that you can custom the annotation of `geom_label` with `label.padding`, `label.size`, `color` and `fill` as described below:
```r
# library
library(ggplot2)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# Add one annotation
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_label(
label="Look at this!",
x=4.1,
y=20,
label.padding = unit(0.55, "lines"), # Rectangle size around label
label.size = 0.35,
color = "black",
fill="#69b3a2"
)
```
<center>
![](https://www.r-graph-gallery.com/275-add-text-labels-with-ggplot2_files/figure-html/thecode3-1.png){width=75%}
</center>
### Add Labels for a Selection of Marker
Last but not least, you can also select a group of marker and annotate them only. Here, only car with `mpg` > 20 and `wt` > 3 are annotated thanks to a data filtering in the `geom_label()` call.
```r
# library
library(ggplot2)
library(dplyr)
library(tibble)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# Change data rownames as a real column called 'carName'
data <- data %>%
rownames_to_column(var="carName")
# Plot
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() +
geom_label(
data=data %>% filter(mpg>20 & wt>3), # Filter data first
aes(label=carName)
)
```
<center>
![](https://www.r-graph-gallery.com/275-add-text-labels-with-ggplot2_files/figure-html/thecode4-1.png){width=75%}
</center>
### How to Annotate a Plot in `ggplot2`
Once your chart is done, annotating it is a crucial step to make it more insightful. This section will guide you through the best practices using `R` and `ggplot2`.
### Adding text with `geom_text()` or `geom_label()`
Text is the most common kind of annotation. It allows to give more information on the most important part of the chart.
Using `ggplot2`, 2 main functions are available for that kind of annotation:
* `geom_text`: to add a simple piece of text.
* `geom_label`: to add a label: framed text.
Note that the `annotate()` function is a good alternative that can reduces the code length for simple cases.
```r
# library
library(ggplot2)
# basic graph
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
# a data frame with all the annotation info
annotation <- data.frame(
x = c(2,4.5),
y = c(20,25),
label = c("label 1", "label 2")
)
# Add text
p + geom_text(data=annotation, aes( x=x, y=y, label=label),
color="orange",
size=7 , angle=45, fontface="bold" )
# Note: possible to shorten with annotate:
# p +
# annotate("text", x = c(2,4.5), y = c(20,25),
# label = c("label 1", "label 2") , color="orange",
# size=7 , angle=45, fontface="bold")
```
<center>
![](https://www.r-graph-gallery.com/233-add-annotations-on-ggplot2-chart_files/figure-html/thecodeA-1.png){width=75%}
</center>
```r
# Right chart: using labels
p + geom_label(data=annotation, aes( x=x, y=y, label=label),
color="orange",
size=7 , angle=45, fontface="bold" )
```
<center>
![](https://www.r-graph-gallery.com/233-add-annotations-on-ggplot2-chart_files/figure-html/thecodeB-1.png){width=75%}
</center>
### Add Shapes with `annotate()`
The `annotate()` function allows to add all kind of shape on a ggplot2 chart. The first argument will control what kind is used: rect or segment for rectangle, segment or arrow.
```r
# Add rectangles
p + annotate("rect", xmin=c(2,4), xmax=c(3,5), ymin=c(20,10) , ymax=c(30,20), alpha=0.2, color="blue", fill="blue")
```
<center>
![](https://www.r-graph-gallery.com/233-add-annotations-on-ggplot2-chart_files/figure-html/thecode1A-1.png){width=75%}
</center>
```r
# Add segments
p + annotate("segment", x = 1, xend = 3, y = 25, yend = 15, colour = "purple", size=3, alpha=0.6)
```
<center>
![](https://www.r-graph-gallery.com/233-add-annotations-on-ggplot2-chart_files/figure-html/thecode1B-1.png){width=75%}
</center>
```r
# Add arrow
p + annotate("segment", x = 2, xend = 4, y = 15, yend = 25, colour = "pink", size=3, alpha=0.6, arrow=arrow())
```
<center>
![](https://www.r-graph-gallery.com/233-add-annotations-on-ggplot2-chart_files/figure-html/thecode1C-1.png){width=75%}
</center>
### Add Ablines with `geom_hline()` and `geom_vline()`
An abline is a segment that goes from one chart extremity to the other. `ggplot2` offers the `geom_hline()` and `geom_vline()` functions that are dedicated to it.
```r
p +
# horizontal
geom_hline(yintercept=25, color="orange", size=1) +
# vertical
geom_vline(xintercept=3, color="orange", size=1)
```
<center>
![](https://www.r-graph-gallery.com/233-add-annotations-on-ggplot2-chart_files/figure-html/thecode2-1.png){width=75%}
</center>
### Add a Point and a Range with `pointrange()`
Last kind of annotation, add a dot and a segment directly with `pointrange()`.
```r
# Add point and range
p + annotate("pointrange", x = 3.5, y = 20, ymin = 12, ymax = 28,colour = "orange", size = 1.5, alpha=0.4)
```
<center>
![](https://www.r-graph-gallery.com/233-add-annotations-on-ggplot2-chart_files/figure-html/thecode3-1.png){width=75%}
</center>
### Marginal Plot
Marginal plots are not natively supported by `ggplot2, but their realisation is straightforward thanks to the `ggExtra` library as illustrated in [graph #277](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2.html).
#### `ggplot2` Scatterplot with Rug
This section demonstrates how to build a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) with rug with `R` and [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html). Adding rug gives insight about variable distribution and is especially helpful when markers overlap.
#### Adding Rug with `geom_rug()`
A [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) displays the relationship between 2 numeric variables. You can easily add rug on X and Y axis thanks to the `geom_rug()` function to illustrate the distribution of dots.
Note you can as well add [marginal plots](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2.html) to show these distributions.
```r
# library
library(ggplot2)
# Iris dataset
head(iris)
# plot
ggplot(data=iris, aes(x=Sepal.Length, Petal.Length)) +
geom_point() +
geom_rug(col="steelblue",alpha=0.1, size=1.5)
```
<center>
![](https://www.r-graph-gallery.com/276-scatterplot-with-rug-ggplot2_files/figure-html/thecode-1.png){width=75%}
</center>
### Marginal Distribution with `ggplot2` and `ggExtra`
This section explains how to add marginal distributions to the X and Y axis of a `ggplot2` [scatterplot](https://www.r-graph-gallery.com/scatterplot.html). It can be done using [histogram](https://www.r-graph-gallery.com/histogram.html), [boxplot](https://www.r-graph-gallery.com/boxplot.html) or [density plot](https://www.r-graph-gallery.com/density-plot.html) using the `ggExtra` library.
#### Basic use of `ggMarginal()`
Here are 3 examples of marginal distribution added on X and Y axis of a scatterplot. The `ggExtra` library makes it a breeze thanks to the `ggMarginal()` function. Three main types of distribution are available: [histogram](https://www.r-graph-gallery.com/histogram.html), [density](https://www.r-graph-gallery.com/density-plot.html) and [boxplot](https://www.r-graph-gallery.com/boxplot.html).
```r
# library
library(ggplot2)
library(ggExtra)
# The mtcars dataset is proposed in R
head(mtcars)
# classic plot :
p <- ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, size=cyl)) +
geom_point() +
theme(legend.position="none")
# with marginal histogram
p1 <- ggMarginal(p, type="histogram")
# marginal density
p2 <- ggMarginal(p, type="density")
# marginal boxplot
p3 <- ggMarginal(p, type="boxplot")
```
```r
p1
```
<center>
![](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2_files/figure-html/unnamed-chunk-1-1.png){width=75%}
</center>
```r
p2
```
<center>
![](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2_files/figure-html/unnamed-chunk-2-1.png){width=75%}
</center>
```r
p3
```
<center>
![](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2_files/figure-html/unnamed-chunk-3-1.png){width=75%}
</center>
### More Customization
Three additional examples to show possible customization:
* Change marginal plot size with `size`.
* Custom marginal plot appearance with all usual parameters.
* Show only one marginal plot with `margins = 'x'` or `margins = 'y'`.
```r
# library
library(ggplot2)
library(ggExtra)
# The mtcars dataset is proposed in R
head(mtcars)
# classic plot :
p <- ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, size=cyl)) +
geom_point() +
theme(legend.position="none")
# Set relative size of marginal plots (main plot 10x bigger than marginals)
p1 <- ggMarginal(p, type="histogram", size=10)
# Custom marginal plots:
p2 <- ggMarginal(p, type="histogram", fill = "slateblue", xparams = list( bins=10))
# Show only marginal plot for x axis
p3 <- ggMarginal(p, margins = 'x', color="purple", size=4)
```
```r
p1
```
<center>
![](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2_files/figure-html/unnamed-chunk-4-1.png){width=75%}
</center>
```r
p2
```
<center>
![](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2_files/figure-html/unnamed-chunk-5-1.png){width=75%}
</center>
```r
p3
```
<center>
![](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2_files/figure-html/unnamed-chunk-6-1.png){width=75%}
</center>
### `ggplot2` Chart Appearance
The `theme()` function of `ggplot2` allows to customize the chart appearance. It controls 3 main types of components:
* [Axis](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2.html): controls the title, label, line and ticks.
* Background: controls the background color and the major and minor grid lines.
* Legend: controls position, text, symbols and more.
#### Axis Manipulation with R and `ggplot2`
This section describes all the available options to customize chart axis with `R` and `ggplot2`. It shows how to control the axis itself, its label, title, position and more.
#### Default `ggplot2` Axis
Let's start with a very basic `ggplot2` [scatterplot](https://www.r-graph-gallery.com/scatterplot.html). The axis usually looks very good with default option as you can see here.
Basically two main functions will allow to customize it:
* `theme()` to change the axis appearance.
* `scale_x_` and `scale_y_` to change the axis type.
Let's see how to use them
```r
# Load ggplot2
library(ggplot2)
# Very basic chart
basic <- ggplot( mtcars , aes(x=mpg, y=wt)) +
geom_point()
basic
```
<center>
![](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2_files/figure-html/thecode-1.png){width=75%}
</center>
### Set Axis Title and Limits with `xlab()` and `xlim()`
Two basic options that are used in almost every charts are `xlab()` and `xlim()` to control the axis title and the axis limits respectively.
<u>Note</u>: it's possible to specify only the lower or upper bound of a limit. For instance, try `xlim(0,NA)`
```r
basic+
xlab("mpg value") +
xlim(0,50)
```
<center>
![](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2_files/figure-html/thecode2-1.png){width=75%}
</center>
### Customize Axis Title Appearance: `axis.title`
The `theme()` function allows to customize all parts of the `ggplot2` chart. The `axis.title`. controls the axis title appearance. Since it is text, features are wrapped in a `element_text()` function. The code below shows how to change the most common features:
```r
basic + theme(axis.title = element_text( angle = 90, color="red", size=15, face=3)) # face = title location
```
<center>
![](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2_files/figure-html/thecode3a-1.png){width=75%}
</center>
```r
basic + theme(axis.title.x = element_text( angle = 90, color="red", size=15, face=3))
```
<center>
![](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2_files/figure-html/thecode3b-1.png){width=75%}
</center>
### Customize Axis Labels: `axis.text`
Using pretty much the same process, the `axis.text()` function allows to control text label features. Once more, using `axis.text.x()` would modify the x axis only.
```r
basic +
theme(axis.text = element_text(
angle = 90,
color="blue",
size=15,
face=3)
)
```
<center>
![](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2_files/figure-html/thecode4-1.png){width=75%}
</center>
### Customize Axis Ticks and Axis Line with `axis.ticks()` and `axis.line()`
The `axis.ticks()` function controls the ticks appearance. `axis.line()` controles the axis line. Both of them are lines, so options are wrapped in a `element_line()` statement.
`linetype` controls the type of line in use, see the [ggplot2 section](https://www.r-graph-gallery.com/ggplot2-package.html) for more.
```r
# chart 1: ticks
basic + theme(
axis.ticks = element_line(size = 2, color="red") ,
axis.ticks.length = unit(.5, "cm")
)
```
<center>
![](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2_files/figure-html/thecode5a-1.png){width=75%}
</center>
```r
# chart 2: axis lines
basic + theme(axis.line = element_line(size = 3, colour = "green", linetype=2))
```
<center>
![](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2_files/figure-html/thecode5b-1.png){width=75%}
</center>
```r
# chart 3: combination
ggplot( mtcars , aes(x=mpg, y=wt)) + geom_point() +
theme(
axis.title = element_text( color="red", size=15, face=2),
axis.line = element_line(size = 3, colour = "green", linetype=2),
axis.text = element_text( angle = 90, color="blue", size=15, face=2)
)
```
<center>
![](https://www.r-graph-gallery.com/238-custom-layout-axis-ggplot2_files/figure-html/thecode5c-1.png){width=75%}
</center>
### Background Manipulation with R and ggplot2
This section describes all the available options to customize chart background with `R` and `ggplot2`. It shows how to control the background color and the minor and major gridlines.
#### Default `ggplot2` Background
Let's start with a very basic `ggplot2` [scatterplot](https://www.r-graph-gallery.com/scatterplot.html). By default, ggplot2 offers a grey background with white major and minor gridlines.
It is possible to change that thanks to the `theme()` function. Keep reading to learn how!
```r
# Load ggplot2
library(ggplot2)
# Very basic chart
basic <- ggplot( mtcars , aes(x=mpg, y=wt)) +
geom_point()
basic
```
<center>
![](https://www.r-graph-gallery.com/240-custom-layout-background-ggplot2_files/figure-html/thecode-1.png){width=75%}
</center>
### Background Color: `plot.background` and `panel.background`
Two options of the `theme()` functions are available to control the map background color. `plot_background` controls the color of the whole chart. `panel.background` controls the part between the axis.
Both are rectangles, with features specified through an `element_rect()` function.
```r
basic + theme(
plot.background = element_rect(fill = "green"),
panel.background = element_rect(fill = "red", colour="blue")
)
```
<center>
![](https://www.r-graph-gallery.com/240-custom-layout-background-ggplot2_files/figure-html/thecode2-1.png){width=75%}
</center>
### Customize the Grid: `panel.grid.major` and `panel.grid.minor`
Two main types of grid exist with `ggplot2`: major and minor. They are controlled thanks to the `panel.grid.major` and `panel.grid.minor` options.
Once more, you can add the options `.y` or `.x` at the end of the function name to control one orientation only.
Features are wrapped in an `element_line()` function. Specifying `element_blanck()` will simply removing the grid.
```r
# Modify for both axis
basic + theme(
panel.grid.major = element_line(colour = "red", linetype = "dotted"),
panel.grid.minor = element_line(colour = "blue", size = 2)
)
```
<center>
![](https://www.r-graph-gallery.com/240-custom-layout-background-ggplot2_files/figure-html/thecode3a-1.png){width=75%}
</center>
```r
# Modify y axis only (remove)
basic + theme(
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank()
)
```
<center>
![](https://www.r-graph-gallery.com/240-custom-layout-background-ggplot2_files/figure-html/thecode3b-1.png){width=75%}
</center>
### Building a Nice Legend with R and `ggplot2`
This section describes all the available options to customize the chart legend with `R` and `ggplot2`. It shows how to control the **title**, **text**, **location**, **symbols** and more.
#### Default Legend with `ggplot2`
By default, `ggplot2` will automatically build a legend on your chart as soon as a shape feature is mapped to a variable in `aes()` part of the `ggplot()` call. So if you use color, shape or alpha, a legend will be available.
Here is an example based on the mtcars dataset. This section is gonna show how to use the `theme()` function to apply all type of customization on this default legend.
<u>Note</u>: this post is strongly inspired by the doc you get typing `ggplot2::theme`, give it a go!
```r
# Load ggplot2
library(ggplot2)
# Very basic chart
basic <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl), shape = factor(vs) )) +
geom_point()
basic
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode-1.png){width=65%}
</center>
### Change Legend Title with `labs()`
The `labs()` function allows to change the legend titles. You can specify one title per section of the legend, i.e. per aesthetics in use in the chart.
```r
basic+
labs(
colour = "name1",
shape = "name2"
)
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode2-1.png){width=65%}
</center>
### Get Rid of the Legend: `guides()` and `theme()`
It is possible to remove a specific part or the whole legend thanks to the `theme()` and the `guides()` function. See code below:
```r
# Left -> get rid of one part of the legend
basic + guides(shape=FALSE)
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode3a-1.png){width=75%}
</center>
```r
# Right -> only the x axis is modified
basic + theme(legend.position = "none")
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode3b-1.png){width=75%}
</center>
### Control Legend Position with `legend.position`
You can place the legend literally anywhere.
To put it around the chart, use the `legend.position` option and specify `top`, `right`, `bottom`, or `left`. To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.
Note: the command `legend.justification` sets the corner that the position refers to.
```r
# Left -> legend around the plot
basic + theme(legend.position = "bottom")
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode4a-1.png){width=75%}
</center>
```r
# Right -> inside the plot area
basic + theme(
legend.position = c(.95, .95),
legend.justification = c("right", "top"),
legend.box.just = "right",
legend.margin = margin(6, 6, 6, 6)
)
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode4b-1.png){width=75%}
</center>
### Legend Appearance
Here are 4 examples showing how to customize the legend main features:
* Box with `legend.box.`: it is a rectangle that frames the legend. Give features with `element_rect()`.
* Key with `legend.key`: the key is the part showing the symbols. Note that symbols will automatically be the ones used on the chart.
* Text with `legend.text`: here you can control the color, the size of the right part of the legend.
* Title with `legend.title`.
```r
# custom box around legend
basic + theme(
legend.box.background = element_rect(color="red", size=2),
legend.box.margin = margin(116, 6, 6, 6)
)
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode5a-1.png){width=55%}
</center>
```r
# custom the key
basic + theme(legend.key = element_rect(fill = "white", colour = "black"))
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode5b-1.png){width=55%}
</center>
```r
# custom the text
basic + theme(legend.text = element_text(size = 8, colour = "red"))
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode5c-1.png){width=55%}
</center>
```r
# custom the title
basic + theme(legend.title = element_text(face = "bold"))
```
<center>
![](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2_files/figure-html/thecode5d-1.png){width=55%}
</center>
### Reorder a Variable with `ggplot2`
This section describes how to reorder a variable in a `ggplot2` chart. Several methods are suggested, always providing examples with reproducible code chunks.
Reordering groups in a `ggplot2` chart can be a struggle. This is due to the fact that ggplot2 takes into account the order of the `factor` levels, not the order you observe in your data frame. You can sort your input data frame with `sort()` or `arrange()`, it will never have any impact on your `ggplot2` output.
This post explains how to reorder the level of your factor through several examples. Examples are based on 2 dummy datasets:
```r
# Library
library(ggplot2)
library(dplyr)
# Dataset 1: one value per group
data <- data.frame(
name=c("north","south","south-east","north-west","south-west","north-east","west","east"),
val=sample(seq(1,10), 8 )
)
# Dataset 2: several values per group (natively provided in R)
# mpg
```
### Method 1: the `Forecats` library
The [Forecats](https://github.com/tidyverse/forcats) library is a library from the [tidyverse](https://www.tidyverse.org/) especially made to handle factors in R. It provides a suite of useful tools that solve common problems with factors. The `fact_reorder()` function allows to reorder the factor (`data$name` for example) following the value of another column (`data$val` here).
```r
# load the library
library(forcats)
# Reorder following the value of another column:
data %>%
mutate(name = fct_reorder(name, val)) %>%
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
coord_flip() +
xlab("") +
theme_bw()
# Reverse side
data %>%
mutate(name = fct_reorder(name, desc(val))) %>%
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
coord_flip() +
xlab("") +
theme_bw()
```
<center>
![](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2_files/figure-html/unnamed-chunk-2-1.png){width=50%}![](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2_files/figure-html/unnamed-chunk-2-2.png){width=50%}
</center>
If you have several values per level of your factor, you can specify which function to apply to determine the order. The default is to use the median, but you can use the number of data points per group to make the classification:
```r
# Using median
mpg %>%
mutate(class = fct_reorder(class, hwy, .fun='median')) %>%
ggplot( aes(x=reorder(class, hwy), y=hwy, fill=class)) +
geom_boxplot() +
xlab("class") +
theme(legend.position="none") +
xlab("")
# Using number of observation per group
mpg %>%
mutate(class = fct_reorder(class, hwy, .fun='length' )) %>%
ggplot( aes(x=class, y=hwy, fill=class)) +
geom_boxplot() +
xlab("class") +
theme(legend.position="none") +
xlab("") +
xlab("")
```
<center>
![](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2_files/figure-html/unnamed-chunk-3-1.png){width=50%}![](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2_files/figure-html/unnamed-chunk-3-2.png){width=50%}
</center>
The last common operation is to provide a specific order to your levels, you can do so using the `fct_relevel()` function as follow:
```r
# Reorder following a precise order
p <- data %>%
mutate(name = fct_relevel(name,
"north", "north-east", "east",
"south-east", "south", "south-west",
"west", "north-west")) %>%
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity") +
xlab("")
#p
```
<center>
![](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2_files/figure-html/unnamed-chunk-5-1.png){width=75%}
</center>
### Method 2: Using `dplyr` Only
The `mutate()` function of `dplyr` allows to create a new variable or modify an existing one. It is possible to use it to recreate a factor with a specific order. Here are 2 examples:
* The first use `arrange()` to sort your data frame, and reorder the factor following this desired order.
* The second specifies a custom order for the factor giving the levels one by one.
```r
data %>%
arrange(val) %>% # First sort by val. This sort the dataframe but NOT the factor levels
mutate(name=factor(name, levels=name)) %>% # This trick update the factor levels
ggplot( aes(x=name, y=val)) +
geom_segment( aes(xend=name, yend=0)) +
geom_point( size=4, color="orange") +
coord_flip() +
theme_bw() +
xlab("")
data %>%
arrange(val) %>%
mutate(name = factor(name, levels=c("north", "north-east", "east", "south-east", "south", "south-west", "west", "north-west"))) %>%
ggplot( aes(x=name, y=val)) +
geom_segment( aes(xend=name, yend=0)) +
geom_point( size=4, color="orange") +
theme_bw() +
xlab("")
```
![](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2_files/figure-html/unnamed-chunk-6-1.png){width=50%}![](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2_files/figure-html/unnamed-chunk-6-2.png){width=50%}
### Method 3: the `reorder()` function of Base R
In case your an unconditional user of the good old R, here is how to control the order using the `reorder()` function inside a `with()` call:
```r
# reorder is close to order, but is made to change the order of the factor levels.
mpg$class = with(mpg, reorder(class, hwy, median))
p <- mpg %>%
ggplot( aes(x=class, y=hwy, fill=class)) +
geom_violin() +
xlab("class") +
theme(legend.position="none") +
xlab("")
#p
```
<center>
![](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2_files/figure-html/unnamed-chunk-8-1.png){width=75%}
</center>
### `ggplot2` Title
The `ggtitle()` function allows to add a title to the chart. The following post will guide you through its usage, showing how to control title main features: position, font, color, text and more.
#### Title Manipulation with R and ggplot2
This section describes all the available options to customize the chart title with `R` and `ggplot2`. It shows how to control its color, its position, and more.
#### Default `ggplot2` Title
It is possible to add a title to a ggplot2 chart using the `ggtitle()` function. It works as follow:
```r
# library & data
library(ggplot2)
data <- data.frame(x=rnorm(100))
# Basic plot with title
ggplot( data=data, aes(x=x)) +
geom_histogram(fill="skyblue", alpha=0.5) +
ggtitle("A blue Histogram") +
theme_minimal()
```
<center>
![](https://www.r-graph-gallery.com/289-control-ggplot2-title_files/figure-html/thecode-1.png){width=75%}
</center>
### Title on Several Lines
It is a common need to set the title on several lines. To add a break and skip to a second line, just add a `\n` in the text.
```r
# title on several lines
ggplot( data=data, aes(x=x)) +
geom_histogram(fill="skyblue", alpha=0.5) +
ggtitle("A blue \nHistogram") +
theme_minimal()
```
<center>
![](https://www.r-graph-gallery.com/289-control-ggplot2-title_files/figure-html/thecode2-1.png){width=75%}
</center>
### Title Appearance and Position
Here are 2 tricks to control text appearance and its position. Both features are controlled thanks to the `plot.title` argument of the `theme()` function. Appearance can be controlled with option such as `family`, `size` or `color`, when position is controlled with `hjust` and `vjust`.
```r
# Custom title appearance
ggplot( data=data, aes(x=x)) +
geom_histogram(fill="skyblue", alpha=0.5) +
ggtitle("A blue Histogram") +
theme_minimal() +
theme(
plot.title=element_text(family='', face='bold', colour='purple', size=26)
)
```
<center>
![](https://www.r-graph-gallery.com/289-control-ggplot2-title_files/figure-html/thecode3a-1.png){width=75%}
</center>
```r
# Adjust the position of title
ggplot( data=data, aes(x=x)) +
geom_histogram(fill="skyblue", alpha=0.8) +
ggtitle("With title on the right") +
theme_minimal() +
theme(
plot.title=element_text( hjust=1, vjust=0.5, face='bold')
)
```
<center>
![](https://www.r-graph-gallery.com/289-control-ggplot2-title_files/figure-html/thecode3b-1.png){width=75%}
</center>
### Customize a Specific Word Only
If you want to highlight a specific set of words in the title, it is double thanks to the `expression()` function.
```r
# Custom a few word of the title only:
my_title <- expression(paste("A ", italic(bold("blue")), " histogram"))
ggplot( data=data, aes(x=x)) +
geom_histogram(fill="skyblue", alpha=0.8) +
ggtitle(my_title) +
theme_minimal()
```
<center>
![](https://www.r-graph-gallery.com/289-control-ggplot2-title_files/figure-html/thecode5-1.png){width=75%}
</center>
### Small Multiples: `facet_wrap()` and `facet_grid()`