-
Notifications
You must be signed in to change notification settings - Fork 24
/
05-legends.Rmd
executable file
·1128 lines (872 loc) · 38.9 KB
/
05-legends.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
# Legends {#legends}
The heatmaps and simple annotations automatically generate legends which are
put one the right side of the heatmap. By default there is no legend for
complex annotations, but they can be constructed and added manually (Section
\@ref(add-customized-legends)). All legends are internally constructed by
`Legend()` constructor. In later sections, we first introduce the settings for
continuous legends and discrete legends, then we will discuss how to configure
the legends associated with the heatmaps and annotations, and how to add new
legends to the plot.
All the legends (no matter a single legend or a pack of legends) all belong to
the `Legends` class. The class only has one slot `grob` which is the real
`grid::grob` object or the `grid::gTree` object that records how to draw the
graphics. The wrapping of the `Legends` class and the methods designed for the
class make legends as single objects and can be drawn like points with
specifying the positions on the viewport.
The legends for heatmaps and annotations can be controlled by
`heatmap_legend_param` argument in `Heatmap()`, or `annotation_legend_param`
argument in `HeatmapAnnotation()`. **Most of the parameters in `Legend()`
function can be directly set in the two arguments with the same parameter
name.** The details of setting heatmap legends and annotation legends
parameters are introduced in Section \@ref(heatmap-and-annotation-legends).
## Continuous legends {#continuous-legends}
Since most of heatmaps contain continuous values, we first introduce the
settings for the continuous legend.
Continuous legend needs a color mapping function which should be generated by
`circlize::colorRamp2()`. In the heatmap legends and annotation legends that
are automatically generated, the color mapping functions are passed by the
`col` argument from `Heatmap()` or `HeatmapAnnotation()` function, while if
you construct a self-defined legend, you need to provide the color mapping
function.
The break values provided in the color mapping function (e.g. `c(0, 0.5, 1)`
in following example) will not exactly be the same as the break values in the
legends). The finally break values presented in the legend are internally
adjusted to make the numbers of labels close to 5 or 6.
First we show the default style of a vertical continuous legend:
```{r}
library(circlize)
col_fun = colorRamp2(c(0, 0.5, 1), c("blue", "white", "red"))
lgd = Legend(col_fun = col_fun, title = "foo")
```
```{r, echo = FALSE}
legend_width = function(lgd) convertWidth(ComplexHeatmap:::width(lgd) + unit(4, "mm"), "inch", valueOnly = TRUE)
legend_height = function(lgd) convertHeight(ComplexHeatmap:::height(lgd) + unit(4, "mm"), "inch", valueOnly = TRUE)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
`lgd` is a `Legends` class object. The size of the legend can be obtained by
`ComplexHeatmap:::width()` and `ComplexHeatmap:::height()` function.
```{r}
ComplexHeatmap:::width(lgd)
ComplexHeatmap:::height(lgd)
```
The legend is actually a packed graphic object composed of rectangles, lines
and texts. It can be added to the plot by `draw()` function. In
**ComplexHeatmap** pacakge, you don't need to use `draw()` directly on legend
objects, but it might be useful if you use the legend objects in other places.
```{r}
pushViewport(viewport(width = 0.9, height = 0.9))
grid.rect() # border
draw(lgd, x = unit(1, "cm"), y = unit(1, "cm"), just = c("left", "bottom"))
draw(lgd, x = unit(0.5, "npc"), y = unit(0.5, "npc"))
draw(lgd, x = unit(1, "npc"), y = unit(1, "npc"), just = c("right", "top"))
popViewport()
```
If you only want to configure the legends generated by heatmaps or
annotations, you don't need to construct the `Legends` object by your own.
**The parameters introduced later can be directly used to customize the
legends by `heatmap_legend_param` argument in `Heatmap()` and
`annotation_legend_param` argument in `HeatmapAnnotation()`** (introduced in
Section
\@ref(heatmap-and-annotation-legends)). It is still nice to see how these parameters change the
styles of the legend in following examples. Following is a simple example
showing how to configure legends in the heatmap and heatmap annotation.
```{r, fig.width = 5.2}
Heatmap(matrix(rnorm(100), 10),
heatmap_legend_param = list(
title = "rnorm", at = c(-2, 0, 2),
labels = c("neg_two", "zero", "pos_two")
),
top_annotation = HeatmapAnnotation(
foo = 1:10,
annotation_legend_param = list(foo = list(title = "foo_top_anno"))
))
```
In following examples, we only show how to construct the legend object, while
not show the code which draws the legends. Only remember you can use `draw()`
function on the `Legends` object to draw the single legend on the plot.
For continuous legend, you can manually adjust the break values in the legend
by setting `at`. Note the height is automatically adjusted.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.25, 0.5, 0.75, 1))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The labels corresponding to the break values are set by `labels`.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.5, 1),
labels = c("low", "median", "high"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The height of the vertical continous legend is set by `legend_height`.
`legend_height` can only be set for the veritcal continous legend and the
value is the height of the legend body (excluding the legend title).
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", legend_height = unit(6, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
If it is a vertical legend, `grid_width` controls the widths of the legend
body. `grid_width` is originally designed for the discrete legends where the
each level in the legend is a grid, but here we use the same name for the
parameter that controls the width of the legend.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", grid_width = unit(1, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The graphic parameters for the labels are controlled by `labels_gp`.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", labels_gp = gpar(col = "red", font = 3))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The border of the legend as well as the ticks for the break values are
controlled by `border`. The value of `border` can be logical or a string of
color.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", border = "red")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
`title_position` controls the position of titles. For vertical legends, the
value should be one of `topleft`, `topcenter`, `lefttop-rot` and
`leftcenter-rot`. Following two plots show the effect of `lefttop-rot` title
and `leftcenter-rot` title.
```{r}
lgd = Legend(col_fun = col_fun, title = "foooooooo", title_position = "lefttop-rot",
legend_height = unit(4, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
```{r}
lgd = Legend(col_fun = col_fun, title = "foooooooo", title_position = "leftcenter-rot",
legend_height = unit(4, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Legend titles and labels can be set as mathematical formulas.
```{r}
lgd = Legend(col_fun = col_fun, title = expression(hat(beta) == (X^t * X)^{-1} * X^t * y),
at = c(0, 0.25, 0.5, 0.75, 1), labels = expression(alpha, beta, gamma, delta, epsilon))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
More complicated texts can be added by using the **gridtext** package (Section \@ref(gridtext-legends)).
```{r}
lgd = Legend(col_fun = col_fun,
title = gt_render("<span style='color:orange'>**Legend title**</span>"),
title_gp = gpar(box_fill = "grey"),
at = c(-3, 0, 3),
labels = gt_render(c("<span style='color:blue'>*negative*</span> three", "zero",
"<span style='color:red'>*positive*</span> three"))
)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Settings for horizontal continuous legends are almost the same as vertical
legends, except that now `legend_width` controls the width of the legend, and
the title position can only be one of `topcenter`, `topleft`, `lefttop` and
`leftcenter`.
The default style for horizontal legend:
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", direction = "horizontal")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Manually set `at`:
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.25, 0.5, 0.75, 1),
direction = "horizontal")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Manually set `labels`:
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.5, 1),
labels = c("low", "median", "high"), direction = "horizontal")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Set `legend_width`:
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", legend_width = unit(6, "cm"),
direction = "horizontal")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Set graphic parameters for labels:
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", labels_gp = gpar(col = "red", font = 3),
direction = "horizontal")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Set rotations of labels.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", labels_rot = 45,
direction = "horizontal")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Title can be set as `topleft`, `topcenter` or `lefttop` and `leftcenter`.
```{r}
lgd = Legend(col_fun = col_fun, title = "foooooooo", direction = "horizontal",
title_position = "topcenter")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
```{r}
lgd = Legend(col_fun = col_fun, title = "foooooooo", direction = "horizontal",
title_position = "lefttop")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
In examples we showed above, the intervals between every two break values are
equal. Actually `at` can also be set as break values with uneuqal intervals.
In this scenario, the ticks on the legend are still at the original places
while the corresponding texts are shifted to get rid of overlapping. Then,
there are lines connecting the ticks and the labels.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.1, 0.15, 0.5, 0.9, 0.95, 1))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
If the labels do not need to be adjusted, they are still at the original places.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.3, 1),
legend_height = unit(4, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
It is similar for the horizontal legends:
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.1, 0.15, 0.5, 0.9, 0.95, 1),
direction = "horizontal")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Set rotations of labels to 90 degree.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.1, 0.15, 0.5, 0.9, 0.95, 1),
direction = "horizontal", title_position = "lefttop", labels_rot = 90)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
When the position of title is set to `lefttop`, the area below the title will
also be taken into account when calculating the adjusted positions of labels.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(0, 0.1, 0.5, 0.75, 1),
labels = c("mininal", "q10", "median", "q75", "maximal"),
direction = "horizontal", title_position = "lefttop")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
If `at` is set in the decreasing order, the legend is reversed, _i.e._ the smallest value
is on the top of the legend.
```{r}
lgd = Legend(col_fun = col_fun, title = "foo", at = c(1, 0.8, 0.6, 0.4, 0.2, 0))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Most continuous legends have legend breaks with equal distance, which I mean,
_e.g._ the distance between the first and the second breaks are the same as the
distance between the second and the third breaks. However, there are still special
cases where users want to set legend breaks with unequal distances.
In the following example, the color mapping function `col_fun_prop` visualizes
proportion values with breaks in `c(0, 0.05, 0.1, 0.5, 1)`. The legend breaks
with unequal distance might reflect the different importance of the values in `c(0, 1)`.
For example, maybe we want to see more details in the interval `c(0, 0.1)`.
Following is the default style of the legend where the breaks are selected from 0 to 1
with equal distance.
```{r}
col_fun_prop = colorRamp2(c(0, 0.05, 0.1, 0.5, 1),
c("green", "white", "red", "black", "blue"))
lgd = Legend(col_fun = col_fun_prop, title = "Prop")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
You cann't see the details in the interval `c(0, 0.1)`, right? This also reminds us that
the breaks set in `colorRamp2()` only defines the color mapping while not determine
the breaks in the legend.
If we manually select the break values, the color bar keeps the same. The labels
are shifted and lines connect them to the original positions. In this case, the distance
in the color bar is still proportional to the real difference in the break values, _i.e._,
the distance between 0.5 and 1 is five times longer than 0 and 0.1.
```{r}
col_fun_prop = colorRamp2(c(0, 0.05, 0.1, 0.5, 1),
c("green", "white", "red", "black", "blue"))
lgd = Legend(col_fun = col_fun_prop, title = "Prop",
at = c(0, 0.05, 0.1, 0.5, 1))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
From version 2.7.1, `Legend()` function has a new argument `break_dist` that
controls the distance between two neighbouring break values in the legend.
**It might be confusing, but from here, when I mention "break distance", it
always means the visual distance in the legend.**
The value of `break_dist` should have length either one which means all break
values have equal distance in the legend, or `length(at) - 1`.
```{r}
lgd = Legend(col_fun = col_fun_prop, title = "Prop", break_dist = 1)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
And in the following example, the top two break intervals are three times longer than
the bottom two intervals.
```{r}
lgd = Legend(col_fun = col_fun_prop, title = "Prop", break_dist = c(1, 1, 3, 3))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
If we increase the legend height by `legend_height` argument, there will be enough space
for the labels and their positions are not adjusted any more.
```{r}
lgd = Legend(col_fun = col_fun_prop, title = "Prop", break_dist = c(1, 1, 3, 3),
legend_height = unit(4, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Imaging following user case, we want to use one color scheme for the values in
`c(0, 0.1)` and a second color schema for the values in `c(0.1, 1)`, maybe for
the reason that we want to emphasize the two intervals are very different. The
color mapping can be defined as:
```{r}
col_fun2 = colorRamp2(c(0, 0.1, 0.1+1e-6, 1), c("white", "red", "yellow", "blue"))
```
So here I just added a tiny shift (`1e-6`) to 0.1 and set it as the lower bound for the
second color scheme. The legend looks like:
```{r}
lgd = Legend(col_fun = col_fun2, title = "Prop", at = c(0, 0.05, 0.1, 0.5, 1),
break_dist = c(1, 1, 3, 3), legend_height = unit(4, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Now you can see the colors are not changed smoothly from 0 to 1 and there are two disticnt
color schemes.
## Discrete legends {#discrete-legends}
Discrete legends are used for discrete color mappings. The continuous color
mapping can also be degenerated as discrete color mapping by only providing
the colors and the break values.
You can either specify `at` or `labels`, but most probably you specify
`labels`. The colors should be specified by `legend_gp`.
```{r}
lgd = Legend(at = 1:6, title = "foo", legend_gp = gpar(fill = 1:6))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
```{r}
lgd = Legend(labels = month.name[1:6], title = "foo", legend_gp = gpar(fill = 1:6))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The discrete legend for continuous color mapping:
```{r}
at = seq(0, 1, by = 0.2)
lgd = Legend(at = at, title = "foo", legend_gp = gpar(fill = col_fun(at)))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The position of title:
```{r}
lgd = Legend(labels = month.name[1:6], title = "foo", legend_gp = gpar(fill = 1:6),
title_position = "lefttop")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
```{r}
lgd = Legend(labels = month.name[1:6], title = "foo", legend_gp = gpar(fill = 1:6),
title_position = "leftcenter-rot")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The size of grids are controlled by `grid_width` and `grid_height`.
```{r}
lgd = Legend(at = 1:6, legend_gp = gpar(fill = 1:6), title = "foo",
grid_height = unit(1, "cm"), grid_width = unit(5, "mm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The graphic parameters of labels are controlled by `labels_gp`.
```{r}
lgd = Legend(labels = month.name[1:6], legend_gp = gpar(fill = 1:6), title = "foo",
labels_gp = gpar(col = "red", fontsize = 14))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The graphic parameters of the title are controlled by `title_gp`.
```{r}
lgd = Legend(labels = month.name[1:6], legend_gp = gpar(fill = 1:6), title = "foo",
title_gp = gpar(col = "red", fontsize = 14))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Title and labels are be complicated texts by integrating **gridtext** package (Section \@ref(gridtext-legends)):
```{r}
lgd = Legend(
title = gt_render("<span style='color:orange'>**Legend title**</span>"),
title_gp = gpar(box_fill = "grey"),
at = c(-3, 0, 3),
labels = gt_render(c("**negative** three", "*zero*", "**positive** three")),
legend_gp = gpar(fill = 1:3)
)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Borders of grids are controlled by `border`.
```{r}
lgd = Legend(labels = month.name[1:6], legend_gp = gpar(fill = 1:6), title = "foo",
border = "red")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
One important thing for the discrete legend is you can arrange the grids into
multiple rows or/and columns. If `ncol` is set to a number, the grids are
arranged into `ncol` columns.
```{r}
lgd = Legend(labels = month.name[1:10], legend_gp = gpar(fill = 1:10),
title = "foo", ncol = 3)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Still the title position is calculated based on the multiplt-column legend.
```{r}
lgd = Legend(labels = month.name[1:10], legend_gp = gpar(fill = 1:10), title = "foo",
ncol = 3, title_position = "topcenter")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
You can choose to list the legend levels by rows by setting `by_row = TRUE`.
```{r}
lgd = Legend(labels = month.name[1:10], legend_gp = gpar(fill = 1:10), title = "foo",
ncol = 3, by_row = TRUE)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The gaps between two columns are controlled by `gap` or `column_gap`. These two arguments
are treated the same.
```{r}
lgd = Legend(labels = month.name[1:10], legend_gp = gpar(fill = 1:10), title = "foo",
ncol = 3, gap = unit(1, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The gaps between rows are controlled by `row_gap`.
```{r}
lgd = Legend(labels = month.name[1:10], legend_gp = gpar(fill = 1:10), title = "foo",
ncol = 3, row_gap = unit(5, "mm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Instead of `ncol`, you can also specify the layout by `nrow`. Note you cannot
use `ncol` and `nrow` at a same time.
```{r}
lgd = Legend(labels = month.name[1:10], legend_gp = gpar(fill = 1:10),
title = "foo", nrow = 3)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
One extreme case is when all levels are put in one row and the title are
rotated by 90 degree. The height of the legend will be the height of the
rotated title.
```{r}
lgd = Legend(labels = month.name[1:6], legend_gp = gpar(fill = 1:6), title = "foooooo",
nrow = 1, title_position = "lefttop-rot")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Following style a lot of people might like:
```{r}
lgd = Legend(labels = month.name[1:6], legend_gp = gpar(fill = 1:6), title = "foooooo",
nrow = 1, title_position = "leftcenter")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
`Legend()` also supports to use simple graphics (e.g. points, lines, boxplots) as
legends. `type` argument can be specified as `points` or `p` that you can use number
for `pch` or single-letter for `pch`.
```{r}
lgd = Legend(labels = month.name[1:6], title = "foo", type = "points",
pch = 1:6, legend_gp = gpar(col = 1:6), background = "#FF8080")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
```{r}
lgd = Legend(labels = month.name[1:6], title = "foo", type = "points",
pch = letters[1:6], legend_gp = gpar(col = 1:6), background = "white")
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Or set `type = "lines"`/`type = "l"` to use lines as legend:
```{r}
lgd = Legend(labels = month.name[1:6], title = "foo", type = "lines",
legend_gp = gpar(col = 1:6, lty = 1:6), grid_width = unit(1, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
Or set `type = "boxplot"`/`type = "box"` to use boxes as legends:
```{r}
lgd = Legend(labels = month.name[1:6], title = "foo", type = "boxplot",
legend_gp = gpar(fill = 1:6))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
When `pch` is an integer number, the numbers in `26:28` correspond to following symbols:
```{r}
lgd = Legend(labels = paste0("pch = ", 26:28), type = "points", pch = 26:28)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
In all examples showed above, the labels are single lines. Multiple-line labels are also
supported. As shown in the following example, legend grids for multiple-line labels are
automatically enlongated.
```{r}
lgd = Legend(labels = c("aaaaa\naaaaa", "bbbbb\nbbbbb", "c", "d"),
legend_gp = gpar(fill = 1:4))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
If the legend is arranged in multiple rows or columns, the sizes of legend grids are adjusted
to the label with the most number of lines.
```{r}
lgd = Legend(labels = c("aaaaa\naaaaa", "c", "d", "bbbbb\nbbbbb"),
legend_gp = gpar(fill = 1:4), nrow = 2)
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
The last useful argument `graphics` can be used to self-define the legend
graphics. The value for `graphics` should be a list of functions with four
arguments: `x` and `y`: the center of the legend grid, `w` and `h`: the width
and height of the legend grid. Length of `graphics` should be the same as `at`
or `labels.` If `graphics` is a named list where the names correspond to
`labels`, then the order of the list of `graphics` is automatically adjusted.
```{r}
lgd = Legend(labels = letters[1:4],
graphics = list(
function(x, y, w, h) grid.rect(x, y, w*0.33, h, gp = gpar(fill = "red")),
function(x, y, w, h) grid.rect(x, y, w, h*0.33, gp = gpar(fill = "blue")),
function(x, y, w, h) grid.text("A", x, y, gp = gpar(col = "darkgreen")),
function(x, y, w, h) grid.points(x, y, gp = gpar(col = "orange"), pch = 16)
))
```
```{r, echo = FALSE, fig.width = legend_width(lgd), fig.height = legend_height(lgd)}
draw(lgd, test = TRUE)
```
## A list of legends {#a-list-of-legends}
A list of legends can be constructed or packed as a `Legends` object where the
individual legends are arranged within a certain layout. The legend list can
be sent to `packLegend()` separatedly or as a list. The legend can be arranged
either vertically or horizontally. **ComplexHeatmap** uses `packLegend()`
internally to arrange multiple legends. Normally you don't need to manually
control the arrangement of multiple legends, but the following section would
be useful if you want to manually construct a list of legends and apply to
other plots.
```{r}
lgd1 = Legend(at = 1:6, legend_gp = gpar(fill = 1:6), title = "legend1")
lgd2 = Legend(col_fun = col_fun, title = "legend2", at = c(0, 0.25, 0.5, 0.75, 1))
lgd3 = Legend(labels = month.name[1:3], legend_gp = gpar(fill = 7:9), title = "legend3")
pd = packLegend(lgd1, lgd2, lgd3)
# which is same as
pd = packLegend(list = list(lgd1, lgd2, lgd3))
```
```{r, echo = FALSE, fig.width = legend_width(pd), fig.height = legend_height(pd)}
draw(pd, test = TRUE)
```
Simillar as single legend, you can draw the packed legends by `draw()`
function. Also you can get the size of `pd` by `ComplexHeatmap:::width()` and
`ComplexHeatmap:::height()`.
```{r}
ComplexHeatmap:::width(pd)
ComplexHeatmap:::height(pd)
```
Horizontally arranging the legends simply by setting `direction = "horizontal"`.
```{r}
pd = packLegend(lgd1, lgd2, lgd3, direction = "horizontal")
```
```{r, echo = FALSE, fig.width = legend_width(pd), fig.height = legend_height(pd)}
draw(pd, test = TRUE)
```
One feature of `packLegend()` is, e.g. if the packing is vertically and the
sum of the packed legends exceeds the height specified by `max_height`, it
will be rearragned as mutliple column layout. In following example, the
maximum height is `10cm`.
When all the legends are put into multiple columns, `column_gap` controls the
space between two columns.
```{r}
pd = packLegend(lgd1, lgd3, lgd2, lgd3, lgd2, lgd1, max_height = unit(10, "cm"),
column_gap = unit(1, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(pd), fig.height = legend_height(pd)}
draw(pd, test = TRUE)
```
Similar for horizontal packing:
```{r}
lgd1 = Legend(at = 1:6, legend_gp = gpar(fill = 1:6), title = "legend1",
nr = 1)
lgd2 = Legend(col_fun = col_fun, title = "legend2", at = c(0, 0.25, 0.5, 0.75, 1),
direction = "horizontal")
pd = packLegend(lgd1, lgd2, lgd3, lgd1, lgd2, lgd3, max_width = unit(10, "cm"),
direction = "horizontal", column_gap = unit(5, "mm"), row_gap = unit(1, "cm"))
```
```{r, echo = FALSE, fig.width = legend_width(pd), fig.height = legend_height(pd)}
draw(pd, test = TRUE)
```
The packed legends `pd` is also a `Legends` object, which means you can use
`draw()` to draw it by specifying the positions.
```{r, fig.width = 7}
pd = packLegend(lgd1, lgd2, lgd3, direction = "horizontal")
pushViewport(viewport(width = 0.8, height = 0.8))
grid.rect()
draw(pd, x = unit(1, "cm"), y = unit(1, "cm"), just = c("left", "bottom"))
draw(pd, x = unit(1, "npc"), y = unit(1, "npc"), just = c("right", "top"))
popViewport()
```
To be mentioned again, `packLegend()` is used internally to manage the list
of heatmap and annotation legends.
## Heatmap and annotation legends {#heatmap-and-annotation-legends}
Settings for heatmap legend are controlled by `heatmap_legend_param` argument
in `Heatmap()`. The value for `heatmap_legend_param` is a list of parameters
which are supported in `Legend()`.
```{r, fig.width = 5.2}
m = matrix(rnorm(100), 10)
Heatmap(m, name = "mat", heatmap_legend_param = list(
at = c(-2, 0, 2),
labels = c("low", "zero", "high"),
title = "Some values",
legend_height = unit(4, "cm"),
title_position = "lefttop-rot"
))
```
`annotation_legend_param` controls legends for annotations. Since a
`HeatmapAnnotation` may contain multiple annotations, the value of
`annotation_legend_param` is a list of configurations of each annotation.
```{r, fig.width = 5.2}
ha = HeatmapAnnotation(foo = runif(10), bar = sample(c("f", "m"), 10, replace = TRUE),
annotation_legend_param = list(
foo = list(
title = "Fooooooh",
at = c(0, 0.5, 1),
labels = c("zero", "median", "one")
),
bar = list(
title = "Baaaaaaar",
at = c("f", "m"),
labels = c("Female", "Male")
)
))
Heatmap(m, name = "mat", top_annotation = ha)
```
If the heatmaps are concatenated horizontally, all heatmap and row annotation
legends are grouped and all column annotation legends ae grouped. The reason
we assume the horizontal direction passes the main message of the plot, while
the vertical direction provides secondary information.
```{r, fig.width = 8}
ha1 = HeatmapAnnotation(foo1 = runif(10), bar1 = sample(c("f", "m"), 10, replace = TRUE))
ha2 = HeatmapAnnotation(foo2 = runif(10), bar2 = sample(c("f", "m"), 10, replace = TRUE))
Heatmap(m, name = "mat1", top_annotation = ha1) +
rowAnnotation(sth = runif(10)) +
Heatmap(m, name = "mat2", top_annotation = ha2)
```
Similarlly, if the heatmaps are concatenated vertically, all heatmaps/column
annotations are grouped and legends for all row annotations are grouped.
```{r, fig.height = 8, fig.width = 5.2}
ha1 = HeatmapAnnotation(foo1 = runif(10), bar1 = sample(c("f", "m"), 10, replace = TRUE),
annotation_name_side = "left")
ha2 = HeatmapAnnotation(foo2 = runif(10), bar2 = sample(c("f", "m"), 10, replace = TRUE))
Heatmap(m, name = "mat1", top_annotation = ha1) %v%
Heatmap(m, name = "mat2", top_annotation = ha2,
right_annotation = rowAnnotation(sth = 1:10))
```
`show_legend` in `HeatmapAnnotation()` and `show_heatmap_legend` in
`Heatmap()` controls whether show the legends. Note `show_legend` can be a
single logical value, a logical vector, or a named vector which controls
subset of annotations.
```{r, fig.width = 8}
ha = HeatmapAnnotation(foo = runif(10),
bar = sample(c("f", "m"), 10, replace = TRUE),
show_legend = c(TRUE, FALSE), # it can also be show_legend = c(bar = FALSE)
annotation_name_side = "left")
Heatmap(m, name = "mat1", top_annotation = ha) +
Heatmap(m, name = "mat2", show_heatmap_legend = FALSE)
```
`merge_legend` in `draw()` function controlls whether to merge all the legends
into a single group. Normally, when there are many annotations and heatmaps,
the number of legends is always large. In this case, the legends are
automatically arranged into multiple columns (or multiple rows if they are put
at the bottom of the heatmaps) to get rid of being out of the figure page. If
a heatmap has heatmap annotations, the order of putting legends are: legends
for the left annotations, legends for the top annotations, legend of the
heatmap, legends for the bottom annotations and legends for the right
annotations.
```{r, fig.width = 8}
ha1 = HeatmapAnnotation(foo1 = runif(10),
bar1 = sample(c("f", "m"), 10, replace = TRUE))
ha2 = rowAnnotation(foo2 = runif(10),
bar2 = sample(letters[1:3], 10, replace = TRUE))
ha3 = rowAnnotation(foo3 = runif(10),
bar3 = sample(month.name[1:3], 10, replace = TRUE))
ht_list = Heatmap(m, name = "mat1", top_annotation = ha1) +
Heatmap(m, name = "mat2", left_annotation = ha2) +