-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathggplot.Rmd
More file actions
2610 lines (1854 loc) · 73.8 KB
/
ggplot.Rmd
File metadata and controls
2610 lines (1854 loc) · 73.8 KB
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: "ggplot2 : title, subtitle, and caption"
output:
html_document:
df_print: paged
---
When using ggplot2 you can set a title, a subtitle, a caption in the plot. There are two ways to add title, subtitle (i) using ggtitle, (ii) using labs function.
# ggtitle
## Title
Let's adding a title of the plot in ggplot2 with ggtitle
```{r}
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
ggtitle("Title of the plot using ggtitle()")
```
### Option 2. Using labs
You can also use the labs function to add the title.
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
labs(title = "Title of the plot using labs()")
```
### Title position
The title position can be set respect to the whole plot instead of the panel with the plot.title.position component of the theme function. Default value is "panel". This configuration also applies to the subtitle.
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
labs(title = "Title on the plot margin") +
theme(plot.title.position = "plot")
```
## Subtitle
You can add a subtitle the same way you added the title, but with the subtitle argument.
### Option 1. Using ggtitle
Add a subtitle in ggplot2
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
ggtitle("Title of the plot",
subtitle = "Subtitle of the plot")
```
### Option 2. Using labs
Subtitle in ggplot2 using labs
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
labs(title = "Title of the plot",
subtitle = "Subtitle of the plot")
```
## Caption
A caption can be used to describe the figure. You can add it with the caption argument of the labs function.
Adding a caption in ggplot2
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
labs(title = "Title of the plot",
subtitle = "Subtitle of the plot",
caption = "This is the caption")
```
The plot.caption.position of the theme function allows aliging the caption to the panel ("panel", default) or the whole plot (“plot”).
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
labs(caption = "This is the caption") +
theme(plot.caption.position = "plot",
plot.caption = element_text(hjust = 0))
```
Changing the caption position in ggplot2
Note that the default for the caption is right alignment, so you can set hjust = 0 to move the caption to the left of the whole plot.
## Tag
Adding a tag to the plot in ggplot2
Tags are useful to indicate the figure numbering. You can add it with the tag argument of the labs function.
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
labs(title = "Title of the plot",
subtitle = "Subtitle of the plot",
caption = "This is the caption",
tag = "Fig. 1")
```
### Tag position
Changing the tag position in ggplot2
The position of the tag can be set with the plot.tag.position component of the theme function. Possible values are "topleft" (default), "top", "topright", "left", "right", "bottomleft", "bottom" or "bottomright".
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
labs(tag = "Fig. 1") +
theme(plot.tag.position = "bottomright")
```
## Further styles and adjustments
The titles, subtitles, captions and tags can be customized with the plot.title, plot.subtitle, plot.caption and plot.tag components of the theme function, making use of element_text. You can modify the color, the font family, the text size, the text face, the angle or the vertical and horizontal adjustment for each text as in the example below.
Styling the titles in ggplot2, such as modifying the color, size, face, family, lineheight and margins
```{r}
# install.packages(ggplot2)
library(ggplot2)
ggplot(economics, aes(date, unemploy)) +
geom_area(fill = rgb(0, 0.5, 1, alpha = 0.5)) +
labs(title = "Title of the plot",
subtitle = "Subtitle of the plot",
caption = "This is the caption",
tag = "Fig. 1") +
theme(plot.title = element_text(family = "serif", # Font family
face = "bold", # Font face
color = 4, # Font color
size = 15, # Font size
hjust = 1, # Horizontal adjustment
vjust = 1, # Vertical adjustment
angle = -10, # Font angle
lineheight = 1, # Line spacing
margin = margin(20, 0, 0, 0)), # Margins (t, r, b, l)
plot.subtitle = element_text(hjust = 0), # Subtitle customization
plot.caption = element_text(hjust = 0.25), # Caption customization
plot.tag = element_text(face = "italic"), # Tag customization
plot.title.position = "plot", # Title and subtitle position ("plot" or "panel")
plot.caption.position = "panel", # Caption position ("plot" or "panel")
plot.tag.position = "top") # Tag position
```
# Text annotations in ggplot2
Adding text with geom_text
Adding labels with geom_label
Avoid overlapping with ggrepel
Use markdown and HTML with ggtext
The geom_text and geom_label functions allows adding text or labels, respectively, to plots created with ggplot2. You can add some annotations to some coordinates or label data points.
```{r}
# install.packages("ggplot2")
library(ggplot2)
# install.packages("maps")
library(maps)
df <- data.frame(x = state.center$x, y = state.center$y,
state = state.name)
p <- ggplot(df, aes(x = x, y = y)) +
geom_polygon(data = map_data("state"),
color = "white",
aes(x = long, y = lat,
fill = map_data("state")$region,
group = group)) +
guides(fill = FALSE)
p
```
In this guide we are going to use the following example plot.
ggplot2 map
Adding text with geom_text
Use the geom_text function to add texts in ggplot2
Adding text annotations
```{r}
p +
geom_text(aes(x = -115, y = 25,
label = "Map of the United States"),
stat = "unique")
```
Set stat = "unique", otherwise the label will be redrawn for each data point on your data frame.
Customize the size and the color of the text using geom_text
Customizing the annotations
There are several arguments that you can customize, such as the color or the size of the text.
```{r}
p +
geom_text(aes(x = -115, y = 25,
label = "Map of the United States"),
stat = "unique",
size = 5, color = "red")
```
Label observations in ggplot2
If your data set contains a variable with groups or labels you can pass it to the label argument.
```{r}
p +
geom_text(aes(label = state))
```
Adding labels with geom_label
If you prefer adding labels instead of raw text use geom_label. The function behaves the same as the previous but with a background, making the text easier to read.
Label annotation
```{r}
p +
geom_label(aes(x = -115, y = 25,
label = "Map of the United States"),
stat = "unique")
```
Use the geom_label function to add labels in ggplot2
Customizing the label
```{r}
p +
geom_label(aes(x = -115, y = 25,
label = "Map of the United States"),
stat = "unique",
size = 5, color = "red", fill = "green")
```
Customize the colors and size of geom_label
Labelling points
```{r}
p +
geom_label(aes(label = state))
```
Labelling observations in ggplot2 with geom_label
Use ggrepel to avoid overlapping of the texts or labels.
Avoid overlapping with ggrepel
The text and the labels are placed on the coordinates you set, but can overlap. The ggrepel package provides geom_text_repel and geom_label_repel functions, which make the labels repel away from each other as much as possible.
geom_text_repel function from ggrepel to avoid overlapping
geom_text_repel
```{r}
# install.packages("ggrepel")
library(ggrepel)
p +
geom_text_repel(aes(label = state))
```
Use the geom_label_repel function to add labels without overlapping in ggplot2
geom_label_repel
```{r}
# install.packages("ggrepel")
library(ggrepel)
p +
geom_label_repel(aes(label = state))
```
You can customize the colors, fonts and other arguments the same way as with geom_text or geom_label. See the package examples for more use cases.
Use markdown and HTML with ggtext
If you want to fully customize you annotations use the geom_richtext function from ggtext, which allows you to add markdown and HTML formatting to your text annotations.
Add rich text
```{r}
# install.packages("ggtext")
library(ggtext)
lab <- "*Map* of <span style = 'color:red'>USA</span>"
p +
geom_richtext(aes(x = -115, y = 25,
label = lab))
```
geom_richtext function to add rich text, HTML and markdown in ggplot2
Rotate the text
You can even rotate the text, a feature that is not available with default ggplot2.
```{r}
# install.packages("ggtext")
library(ggtext)
lab <- "*Map* of <span style = 'color:red'>USA</span>"
p +
geom_richtext(aes(x = -115, y = 27,
label = lab),
angle = 25)
```
Rotate labels or texts in ggplot2
# Background color in ggplot2
## Panel background color
## Panel border color
## Plot background color
## Plot border color
Changing the colors with themes
Color picker
Default plot
By default, ggplot2 plots have a gray panel and a white background.
```{r}
library(ggplot2)
# Sample data
set.seed(123)
x <- 1:220
y <- x + rnorm(220, sd = 50)
df <- data.frame(x = x, y = y)
# Plot
ggplot(data = df, aes(x = x, y = y)) +
geom_point()
```
Default background color in ggplot2
Panel background color
You can change the panel background color setting an element_rect in the panel.background component of the theme function as follows.
Change the background panel color in ggplot2
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = mpg, y = cyl))+
geom_point() +
theme(panel.background = element_rect(fill = "#67c9ff"))
```
Panel border color
Option 1
ggplot2 panel border color
The panel.border component of the theme function controls the color and width of the border of the panel with the color and size arguments. However, you will need to set fill = "transparent" to avoid hiding the data.
```{r}
library(ggplot2)
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
theme_bw() +
theme(panel.border = element_rect(fill = "transparent", # Needed to add the border
color = 4, # Color of the border
size = 2)) # Border width
```
Option 2
Border color of the plot in ggplot2
You can also set a element_rect for the panel.background component and modify the border color with the color argument. However, this is not the recommended workflow, as it doesn’t override the current border. You can check this with theme_bw (Note that the black border is behind the blue border).
```{r}
library(ggplot2)
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
theme_bw() +
theme(panel.background = element_rect(color = 4, # Color of the border
size = 2)) # Border width
```
Plot background color
The plot.background component of the theme function allows modifying the background color of the figure. Set the color inside the fill argument of an element_rect.
Plot background color in ggplot2
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = mpg, y = cyl))+
geom_point() +
theme(plot.background = element_rect(fill = "gray86")) # Background color of the plot
```
Plot border color
Plot border color in ggplot
You can also set a border color for the whole figure. Just pass an element_rect to the plot.background component of the theme function and modify the color and the width of the border with the arguments color and size, respectively.
```{r}
library(ggplot2)
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
theme(plot.background = element_rect(color = "black", # Border color
size = 2)) # Border width
```
Changing the colors with themes
It is worth mentioning that there are lots of ggplot themes available that provide different background colors.
In this example we are setting the theme_dark, which is one of the in-built ggplot2 themes.
```{r}
library(ggplot2)
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
theme_dark()
```
Note that the default theme is theme_grey.
Change the color of a plot with a ggplot theme
Color picker
Use the color pickers to change the panel color (left) and the plot color (right), or to generate random colors pressing the blue button. Then you can copy the colors and use them in your plots.
#EBEBEB
#FFFFFF
Generate random
# Grid customization in ggplot2
Grid customization
Major grid
Minor grid
Custom grid breaks
Remove grids
By default, ggplot2 creates a major and a minor white grid as shown in the following figure.
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg))+
geom_point()
```
Default ggplot2 grid
Grid customization
Grid customization in ggplot2
The grid aesthetics can be set with the panel.grid component of the theme function. Customize the color, line width and line type with the arguments of the element_line function.
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid = element_line(color = "#8ccde3",
size = 0.75,
linetype = 2))
```
You can also customize the major grid and the minor grid individually, as shown in the following sections.
Major grid
The panel.grid.major allows you to customize the major grid of the panel.
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid.major = element_line(color = "red",
size = 0.5,
linetype = 2))
```
Major grid in ggplot2
Appending .x or .y to the previous component will allow customizing the vertical and horizontal lines of the major grid.
Vertical lines of the major grid
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid.major.x = element_line(color = "red",
size = 0.5,
linetype = 2))
```
Vertical lines of the major grid in ggplot2
Horizontal lines of the major grid
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid.major.y = element_line(color = "red",
size = 0.5,
linetype = 2))
```
Horizontal lines of the major grid in ggplot
Minor grid
Minor grid in ggplot2
The panel.grid.minor allows you to customize the minor grid of the panel.
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid.minor = element_line(color = 2,
size = 0.25,
linetype = 1))
```
As in the previous section, you can append .x or .y to the theme element.
Minor grid of the X-axis in ggplot2
Vertical lines of the minor grid
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid.minor.x = element_line(color = 2,
size = 0.25,
linetype = 1))
```
Minor grid of the Y-axis in ggplot2
Horizontal lines of the minor grid
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid.minor.y = element_line(color = 2,
size = 0.25,
linetype = 1))
```
Custom grid breaks
The number of grid breaks can be customized in ggplot for each axis with the breaks argument of the scale_(x|y)_continuous or scale_(x|y)_discrete functions, depending on if the variable of the (x|y)-axis is continuous or discrete.
In this example you can customize the breaks of the Y-axis with the scale_y_continuous function as follows.
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
scale_y_continuous(breaks = seq(10, 35, by = 1))
```
Custom grid breaks in ggplot2 with scale_y_continuous
As the X-axis is also continuous you can make use of the scale_x_continuous to customize the grid breaks of the X-axis.
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
scale_x_continuous(breaks = seq(50, 350, by = 25))
```
Custom grid breaks X-axis with scale_x_continuous
Set minor breaks with minor_breaks argument.
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
scale_x_continuous(breaks = seq(50, 350, by = 25),
minor_breaks = seq(50, 350, 10))
```
Minor breaks in ggplot2
Set the number of major breaks with n.breaks argument.
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
scale_x_continuous(n.breaks = 20)
```
The algorithm behind the generation of major breaks may choose a different number than the specified to ensure nice break labels.
Number of breaks in ggplot
Remove grids
The same way you customized each grid (panel.grid, panel.major, panel.major.x, panel.major.y, panel.minor, panel.minor.x, panel.minor.y) you can remove them but setting element_blank instead of element_line.
Remove grid in ggplot2
Remove all grids
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid = element_blank())
```
Remove the major grid in ggplot2
Remove the major grid
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid.major = element_blank())
```
Remove the minor grid in ggplot2
Remove the minor grid
```{r}
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
theme(panel.grid.minor = element_blank())
```
# Margins in ggplot2
Increase margins
Remove margins
The margins of the plots made with ggplot2 will adjust automatically to new layers, e.g. if you add a title. We have added a black box around the sample plot so you can see how margins change.
```{r}
library(ggplot2)
ggplot() +
stat_function(fun = dnorm, geom = "density",
xlim = c(-4, 4),
fill = rgb(0, 0, 1, 0.1)) +
theme(plot.background = element_rect(color = 1,
size = 1))
```
Default margins in ggplot2
Increase margins
Increase the ggplot2 margins in points
In order to modify the plot margins set the margin function inside the plot.margin component of the theme function.
```{r}
library(ggplot2)
ggplot() +
stat_function(fun = dnorm, geom = "density",
xlim = c(-4, 4),
fill = rgb(0, 0, 1, 0.1)) +
theme(plot.background = element_rect(color = 1,
size = 1),
plot.margin = margin(t = 20, # Top margin
r = 50, # Right margin
b = 40, # Bottom margin
l = 10)) # Left margin
```
Increase the margins in centimeters in ggplot2
The margins are measured with points ("pt"), but you can use other unit measure in the unit argument, like centimeters. Type ?unit to see all the possible measures.
```{r}
library(ggplot2)
ggplot() +
stat_function(fun = dnorm, geom = "density",
xlim = c(-4, 4),
fill = rgb(0, 0, 1, 0.1)) +
theme(plot.background = element_rect(color = 1,
size = 1),
plot.margin = margin(t = 1, # Top margin
r = 1, # Right margin
b = 3, # Bottom margin
l = 2, # Left margin
unit = "cm"))
```
Remove margins
To remove the margins set all values to 0. Note that there is still space to fit all the elements of the plot. You can set negative values to reduce more the margins.
```{r}
library(ggplot2)
ggplot() +
stat_function(fun = dnorm, geom = "density",
xlim = c(-4, 4),
fill = rgb(0, 0, 1, 0.1)) +
theme(plot.background = element_rect(color = 1,
size = 1),
plot.margin = margin(t = 0, # Top margin
r = 0, # Right margin
b = 0, # Bottom margin
l = 0)) # Left margin
```
Remove the margins in ggplot2
You can remember the order of the arguments of the margin function (t, r, b, l) remembering the word trouble.
# Legends in ggplot2
Sample data
Adding a legend
Change or remove the title of the legend
Change or reorder the labels of the legend
Change the position of the legend
Legend customization
Remove the legend
Sample data
In this tutorial we are going to use the following sample data categorized into two groups.
```{r}
# Data
set.seed(1)
df <- data.frame(x = c(rnorm(300, -3, 1.5),
rnorm(300, 0, 1)),
group = c(rep("A", 300),
rep("B", 300)))
```
Adding a legend
If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color, fill, shape or alpha inside aes. Depending on which argument you use to pass the data and your specific case the output will be different.
Color
Passing the categorical variable to color inside aes the data will be plotted based on groups and an automatic legend will you up.
```{r}
# install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = x, color = group)) +
geom_density(alpha = 0.5)
```
Plot with default legend in ggplot2
Note that this is the argument you should use if you want to create a plot that doesn’t admit a fill color, such as a scatter plot. You can pass a categorical or a numerical variable.
```{r}
# install.packages("ggplot2")
library(ggplot2)
# Data
x <- runif(200)
y <- 3 * x ^ 2 + rnorm(length(x), sd = 2.5)
group <- ifelse(x < 0.5, "A", "B")
df2 <- data.frame(x = x, y = y, group = group)
ggplot(df2, aes(x = x, y = y, color = group)) +
geom_point()
```
Scatter plot with legend in ggplot2
Alpha
```{r}
# install.packages("ggplot2")
library(ggplot2)
# Data
x <- runif(200)
y <- 3 * x ^ 2 + rnorm(length(x), sd = 2.5)
group <- ifelse(x < 0.5, "A", "B")
df2 <- data.frame(x = x, y = y)
ggplot(df2, aes(x = x, y = y, alpha = y)) +
geom_point(colour = 4)
```
Scatter plot with legend based on transparency in ggplot2
Fill
If the plot you are creating allows adding a fill color you can use the fill argument inside aes, so the boxes of the legend will be colored.
```{r}
# install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = x, fill = group)) +
geom_density(alpha = 0.5)
```
Legend by fill color in ggplot2
Color and fill at the same time
In the previous scenario you can also use both arguments (fill and color), so the legend will be a box filled with the correspoding color and the border will also have the corresponding color of the group.
```{r}
# install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = x, fill = group, color = group)) +
geom_density(alpha = 0.5)
```
Fill and color ggplot2 legend
If you want to change the fill or border colors of the chart (and automatically of the legend) take a look to other tutorials, such as the density plot by group tutorial.
Change or remove the title of the legend
There are several ways to change the title of the legend of your plot. Note that the chosen option will depend on your chart type and your preferences.
Changing the title of the legend in ggplot2 with guides
Option 1
The first option is using the guides function and passing guide_legend to fill or to color, depending on your plot.
```{r}
# install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = x, fill = group)) +
geom_density(alpha = 0.5) +
guides(fill = guide_legend(title = "Title"))
```
Modifying the title of the legend in ggplot2 with the labs function
Option 2
The second option is passing the new title to the fill or color argument of the labs function.
```{r}
# install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = x, fill = group)) +
geom_density(alpha = 0.5) +
labs(fill = "Title")
```
Customizing the legend title in ggplot2 with a scale
Option 3
The third option is passing the new title to the name argument of the corresponding “scale_x_y” functions, such as scale_fill_discrete or scale_color_discrete, if you are using them in your plot.
```{r}
# install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = x, fill = group)) +
geom_density(alpha = 0.5) +
scale_fill_discrete(name = "Title")
```
Remove the ggplot2 legend title
Removing the title
Finally, if you prefer removing the title of the legend just pass the element_blank function to the legend.title argument of theme.
```{r}
# install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = x, fill = group)) +
geom_density(alpha = 0.5) +
theme(legend.title = element_blank())
```
Change or reorder the labels of the legend
If you want to change the group names of the legend you can customize the data frame column representing the groups.
Other option is passing the new labels to the labels argument of the scale_color_hue or scale_fill_hue functions to modify only the labels or using scale_color_discrete or scale_fill_discrete functions if you also want to change the colors.
New legend group labels
```{r}
# install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = x, fill = group)) +
geom_density(alpha = 0.5) +
scale_fill_hue(labels = c("G1", "G2"))
```
Customizing the legend labels in ggplot2
Reorder the labels
In case you want to reorder the labels of the legend you will need to reorder the factor variable. In this example we have created a new variable with the new order.
```{r}
# install.packages("ggplot2")
library(ggplot2)
# Create a new variable with other levels
df$group2 <- factor(df$group,
levels = c("B", "A"))
ggplot(df, aes(x = x, fill = group2)) +
geom_density(alpha = 0.5)
```
Reorder of the labels of the ggplot2 legend
Change the position of the legend
By default, the automatic legend of a ggplot2 chart is displayed on the right of the plot. However, making use of the legend.position argument of the theme function you can modify its position. Possible values are "right" (default), "top", "left", "bottom" and "none".
Legend at the top of the chart in ggplot2
Top
```{r}