-
Notifications
You must be signed in to change notification settings - Fork 24
/
03-heatmap_annotations.Rmd
executable file
·2747 lines (2198 loc) · 92.1 KB
/
03-heatmap_annotations.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
```{r, echo = FALSE}
annotation_width = function(ha) {
if(identical(ComplexHeatmap:::width(ha), unit(1, "npc"))) {
6
} else {
convertWidth(ComplexHeatmap:::width(ha) + unit(4, "mm"), "inch", valueOnly = TRUE)
}
}
annotation_height = function(ha) {
if(identical(ComplexHeatmap:::height(ha), unit(1, "npc"))) {
6
} else {
convertHeight(ComplexHeatmap:::height(ha) + unit(4, "mm"), "inch", valueOnly = TRUE)
}
}
```
# Heatmap Annotations {#heatmap-annotations}
Heatmap annotations are important components of a heatmap that it shows
additional information that associates with rows or columns in the heatmap.
**ComplexHeatmap** package provides very flexible supports for setting
annotations and defining new annotation graphics. The annotations can be put
on the four sides of the heatmap, by `top_annotation`, `bottom_annotation`,
`left_annotation` and `right_annotation` arguments.
The value for the four arguments should be in the `HeatmapAnnotation` class
and should be constructed by `HeatmapAnnotation()` function, or by
`rowAnnotation()` function if it is a row annotation. (`rowAnnotation()` is
just a helper function which is identical to `HeatmapAnnotation(..., which =
"row")`). A simple usage of heatmap annotations is as follows.
```{r, fig.width = 5.2}
set.seed(123)
mat = matrix(rnorm(100), 10)
rownames(mat) = paste0("R", 1:10)
colnames(mat) = paste0("C", 1:10)
column_ha = HeatmapAnnotation(foo1 = runif(10), bar1 = anno_barplot(runif(10)))
row_ha = rowAnnotation(foo2 = runif(10), bar2 = anno_barplot(runif(10)))
Heatmap(mat, name = "mat", top_annotation = column_ha, right_annotation = row_ha)
```
Or assign as bottom annotation and left annotation.
```{r, fig.width = 5.2}
Heatmap(mat, name = "mat", bottom_annotation = column_ha, left_annotation = row_ha)
```
In above examples, `column_ha` and `row_ha` both have two annotations where
`foo1` and `foo2` are numeric vectors and `bar1` and `bar2` are barplots. The
vector-like annotation is called _"simple annotation"_ here and the barplot
annotation is called _"complex annotation"_. You can already see the
annotations must be defined as name-value pairs (e.g. `foo = ...`).
Heatmap annotations can also be independent of the heatmaps. They can be
concatenated to the heatmap list by `+` if it is horizontal, or `%v%` if it is
vertical. Chapter \@ref(a-list-of-heatmaps) will discuss how to concatenate
heatmaps and annotations.
```{r, eval = FALSE}
# code only for demonstration
Heatmap(...) + rowAnnotation() + ...
Heatmap(...) %v% HeatmapAnnotation(...) %v% ...
```
`HeatmapAnnotation()` returns a `HeatmapAnnotation` class object. The object
is usually composed of several annotations. In the following sections of this
chapter, we first introduce settings for individal annotation, and later we
show how to put them toghether.
You can see the information of the `column_ha` and `row_ha` objects by directly enter the object names:
```{r}
column_ha
row_ha
```
In the following examples in this chapter, we will only show the graphics for the
annotations with no heatmap, unless it is necessary. If you want to try it
with a heatmap, you just assign the `HeatmapAnnotation` object which we always
name as `ha` to `top_annotation`, `bottom_annotation`, `left_annotation` or
`right_annotation` arguments.
Settings are basically the same for column annotations and row annotations. If
there is nothing specicial, we only show the column annotation as examples. If
you want to try row annotation, just add `which = "row"` to
`HeatmapAnnotation()` or directly change to `rowAnnotation()` function.
## Simple annotation {#simple-annotation}
A so-called _"simple annotation"_ is the most used style of annotations which
is heatmap-like or grid-like graphics where colors are used to map to the
annotation values. To generate a simple annotation, you just simply put the
annotation vector in `HeatmapAnnotation()` with a certain name.
```{r}
ha = HeatmapAnnotation(foo = 1:10)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Or a discrete annotation:
```{r}
ha = HeatmapAnnotation(bar = sample(letters[1:3], 10, replace = TRUE))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
You can use any strings as annotation names except those pre-defined arguments
in `HeatmapAnnotation()`.
If colors are not specified, colors are randomly generated. To set colors for
annotations, `col` needs to be set as a named list where the names should be
the same as annotation names. For continuous values, the color mapping should
be a color mapping function generated by `circlize::colorRamp2()`.
```{r}
library(circlize)
col_fun = colorRamp2(c(0, 5, 10), c("blue", "white", "red"))
ha = HeatmapAnnotation(foo = 1:10, col = list(foo = col_fun))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
And for discrete annotations, the color should be a named vector where names
correspond to the levels in the annotation.
```{r}
ha = HeatmapAnnotation(bar = sample(letters[1:3], 10, replace = TRUE),
col = list(bar = c("a" = "red", "b" = "green", "c" = "blue")))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
If you specify more than one vectors, there will be multiple annotations
(`foo` and `bar` in following example). Also you can see how `col` is set when
`foo` and `bar` are all put into a single `HeatmapAnnotation()`. Maybe now you
can understand the names in the color list is actually used to map to the
annotation names. Values in `col` will be used to construct legends for simple
annotations.
```{r}
ha = HeatmapAnnotation(
foo = 1:10,
bar = sample(letters[1:3], 10, replace = TRUE),
col = list(foo = col_fun,
bar = c("a" = "red", "b" = "green", "c" = "blue")
)
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
The color for `NA` value is controlled by `na_col` argument.
```{r}
ha = HeatmapAnnotation(
foo = c(1:4, NA, 6:10),
bar = c(NA, sample(letters[1:3], 9, replace = TRUE)),
col = list(foo = col_fun,
bar = c("a" = "red", "b" = "green", "c" = "blue")
),
na_col = "black"
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
`gp` mainly controls the graphics parameters for the borders of the grids.
```{r}
ha = HeatmapAnnotation(
foo = 1:10,
bar = sample(letters[1:3], 10, replace = TRUE),
col = list(foo = col_fun,
bar = c("a" = "red", "b" = "green", "c" = "blue")
),
gp = gpar(col = "black")
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
The simple annotation can also be a matrix (numeric or character) that all the
columns in the matrix share a same color mapping schema. **Note columns in the
matrix correspond to the rows in the column annotation** (you can imagine a vector is a one-column matrix). Also the column
names of the matrix are used as the annotation names.
```{r}
ha = HeatmapAnnotation(foo = cbind(a = runif(10), b = runif(10)))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
If the matrix has no column name, the name of the annotation is still used, but drawn
in the middle of the annotation.
```{r}
ha = HeatmapAnnotation(foo = cbind(runif(10), runif(10)))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
As simple annotations can be in different modes (e.g. numeric, or character),
they can be combined as a data frame and send to `df` argument. Imagine in your
project, you might already have an annotation table, you can directly set it by
`df`.
```{r}
anno_df = data.frame(
foo = 1:10,
bar = sample(letters[1:3], 10, replace = TRUE)
)
ha = HeatmapAnnotation(df = anno_df,
col = list(foo = col_fun,
bar = c("a" = "red", "b" = "green", "c" = "blue")
)
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Single annotations and data frame can be mixed, but single annotations are
inserted after the data frame annotation. In following example, colors for
`foo2` is not specified, random colors will be used.
```{r}
ha = HeatmapAnnotation(df = anno_df,
foo2 = rnorm(10),
col = list(foo = col_fun,
bar = c("a" = "red", "b" = "green", "c" = "blue")
)
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
`border` controls the border of every single annotation.
```{r}
ha = HeatmapAnnotation(
foo = cbind(1:10, 10:1),
bar = sample(letters[1:3], 10, replace = TRUE),
col = list(foo = col_fun,
bar = c("a" = "red", "b" = "green", "c" = "blue")
),
border = TRUE
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
The height of the simple annotation is controlled by `simple_anno_size`
argument. Since all single annotations have same height, the value of
`simple_anno_size` is a single `unit` value. Note there are arguments like
`width`, `height`, `annotation_width` and `annotation_height`, but they are
used to adjust the width/height for the complete heamtap annotations (which
are always mix of several annotations). The adjustment of these four arguments
will be introduced in Section \@ref(multiple-annotations).
```{r}
ha = HeatmapAnnotation(
foo = cbind(a = 1:10, b = 10:1),
bar = sample(letters[1:3], 10, replace = TRUE),
col = list(foo = col_fun,
bar = c("a" = "red", "b" = "green", "c" = "blue")
),
simple_anno_size = unit(1, "cm")
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
When you have multiple heatmaps and it is better to keep the size of simple
annotations on all heatmaps with the same size. `ht_opt$simple_anno_size` can
be set to control the simple annotation size globally (It will be introduced
in Section \@ref(change-parameters-globally)).
## Simple annotation as an annotation function {#simple-annotation-as-an-annotation-function}
`HeatmapAnnotation()` supports _"complex annotation"_ by setting the
annotation as a function. The annotation function defines how to draw the
graphics at a certain position corresponding to the column or row in the
heatmap. There are quite a lot of annotation functions predefined in
**ComplexHeatmap** package. In the end of this chapter, we will introduce how
to construct your own annotation function by the `AnnotationFunction` class.
For all the annotation functions in forms of `anno_*()`, if it is specified in
`HeatmapAnnotation()` or `rowAnnotation()`, you don't need to do anything
explicitly on `anno_*()` to tell whether it should be drawn on rows or
columns. `anno_*()` automatically detects whether it is a row annotation
environment or a column annotation environment.
The simple annotation shown in previous section is internally constructed by
`anno_simple()` annotation function. Directly using `anno_simple()` **will not
automatically generate legends for the final plot**, but, it can provide more
flexibility for more annotation graphics (note in Chapter
\@ref(legends) we will show, although `anno_simple()` cannot automatically generate the
legends, the legends can be controlled and added to the final plot manually).
For an example in previous section:
```{r, eval = FALSE}
# code only for demonstration
ha = HeatmapAnnotation(foo = 1:10)
```
is actually identical to:
```{r, eval = FALSE}
# code only for demonstration
ha = HeatmapAnnotation(foo = anno_simple(1:10))
```
`anno_simple()` makes heatmap-like annotations (or the simple annotations).
Basically if users only make heatmap-like annotations, they do not need to
directly use `anno_simple()`, but this function allows to add more symbols on
the annotation grids.
`anno_simple()` allows to add "points" or single-letter symbols on top of the
annotation grids. `pch`, `pt_gp` and `pt_size` control the settings of the
points. The value of `pch` can be a vector with possible `NA` values.
```{r}
ha = HeatmapAnnotation(foo = anno_simple(1:10, pch = 1,
pt_gp = gpar(col = "red"), pt_size = unit(1:10, "mm")))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Set `pch` as a vector:
```{r}
ha = HeatmapAnnotation(foo = anno_simple(1:10, pch = 1:10))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Set `pch` as a vector of letters:
```{r}
ha = HeatmapAnnotation(foo = anno_simple(1:10,
pch = sample(letters[1:3], 10, replace = TRUE)))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Set `pch` as a vector with `NA` values (nothing is drawn for `NA` pch values):
```{r}
ha = HeatmapAnnotation(foo = anno_simple(1:10, pch = c(1:4, NA, 6:8, NA, 10, 11)))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
`pch` also works if the value for `anno_simple()` is a matrix. The length of
`pch` should be as same as the number of matrix rows or columns or even the
length of the matrix (the length of the matrix is the length of all data
points in the matrix).
Length of `pch` corresponds to matrix columns:
```{r}
ha = HeatmapAnnotation(foo = anno_simple(cbind(1:10, 10:1), pch = 1:2))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Length of `pch` corresponds to matrix rows:
```{r}
ha = HeatmapAnnotation(foo = anno_simple(cbind(1:10, 10:1), pch = 1:10))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
`pch` is a matrix:
```{r}
pch = matrix(1:20, nc = 2)
pch[sample(length(pch), 10)] = NA
ha = HeatmapAnnotation(foo = anno_simple(cbind(1:10, 10:1), pch = pch))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Till now, you might wonder how to set the legends of the symbols you've added
to the simple annotations. Here we will only show you a simple example and
this functionality will be discussed in Chapter \@ref(legends). In following
example, we assume the simple annotations are kind of p-values and we add `*`
for p-values less than 0.01.
```{r, fig.width = 5.2}
set.seed(123)
pvalue = 10^-runif(10, min = 0, max = 3)
is_sig = pvalue < 0.01
pch = rep("*", 10)
pch[!is_sig] = NA
# color mapping for -log10(pvalue)
pvalue_col_fun = colorRamp2(c(0, 2, 3), c("green", "white", "red"))
ha = HeatmapAnnotation(
pvalue = anno_simple(-log10(pvalue), col = pvalue_col_fun, pch = pch),
annotation_name_side = "left")
ht = Heatmap(matrix(rnorm(100), 10), name = "mat", top_annotation = ha)
# now we generate two legends, one for the p-value
# see how we define the legend for pvalue
lgd_pvalue = Legend(title = "p-value", col_fun = pvalue_col_fun, at = c(0, 1, 2, 3),
labels = c("1", "0.1", "0.01", "0.001"))
# and one for the significant p-values
lgd_sig = Legend(pch = "*", type = "points", labels = "< 0.01")
# these two self-defined legends are added to the plot by `annotation_legend_list`
draw(ht, annotation_legend_list = list(lgd_pvalue, lgd_sig))
```
The height of the simple annotation can be controlled by `height` argument or
`simple_anno_size` inside `anno_simple()`. `simple_anno_size` controls the
size for single-row annotation and `height`/`width` controls the total
height/width of the simple annotations. If `height`/`width` is set,
`simple_anno_size` is ignored.
```{r}
ha = HeatmapAnnotation(foo = anno_simple(1:10, height = unit(2, "cm")))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
```{r}
ha = HeatmapAnnotation(foo = anno_simple(cbind(1:10, 10:1),
simple_anno_size = unit(2, "cm")))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
**For all the annotation functions we introduce later, the height or the width
for individual annotations should all be set inside the `anno_*()`
functions.**
```{r, eval = FALSE}
# code only for demonstration
anno_*(..., width = ...)
anno_*(..., height = ...)
```
Again, the `width`, `height`, `annotation_width` and `annotation_height`
arguments in `HeatmapAnnotation()` are used to adjust the size of multiple
annotations.
## Empty annotation {#empty-annotation}
`anno_empty()` is a place holder where nothing is drawn. Later user-defined
graphics can be added by `decorate_annotation()` function.
```{r}
ha = HeatmapAnnotation(foo = anno_empty(border = TRUE))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, index = 1:10, test = TRUE)
```
In Chapter \@ref(heatmap-decoration), we will introduce the use of the
decoration functions, but here we give a quick example. In gene expression
expression analysis, there are senarios that we split the heatmaps into
several groups and we want to highlight some key genes in each group. In this
case, we simply add the gene names on the right side of the heatmap without
aligning them to the their corresponding rows. (`anno_mark()` can align the
labels correclty to their corresponding rows, but in the example we show here,
it is not necessray).
In following example, since rows are split into four slices, the empty
annotation is also split into four slices. Basically what we do is in each
empty annotation slice, we add a colored segment and text.
```{r, fig.width = 5.2}
random_text = function(n) {
sapply(1:n, function(i) {
paste0(sample(letters, sample(4:10, 1)), collapse = "")
})
}
text_list = list(
text1 = random_text(4),
text2 = random_text(4),
text3 = random_text(4),
text4 = random_text(4)
)
# note how we set the width of this empty annotation
ha = rowAnnotation(foo = anno_empty(border = FALSE,
width = max_text_width(unlist(text_list)) + unit(4, "mm")))
Heatmap(matrix(rnorm(1000), nrow = 100), name = "mat", row_km = 4, right_annotation = ha)
for(i in 1:4) {
decorate_annotation("foo", slice = i, {
grid.rect(x = 0, width = unit(2, "mm"), gp = gpar(fill = i, col = NA), just = "left")
grid.text(paste(text_list[[i]], collapse = "\n"), x = unit(4, "mm"), just = "left")
})
}
```
Note the previous plot can also be made by `anno_block()` or `anno_textbox()` (Section \@ref(anno-text-box)).
A second use of the empty annotation is to add complex annotation graphics
where the empty annotation pretends to be a virtual plotting region. You can
construct an annotation function by `AnnotationFunction` class for complex
annotation graphics, which allows subsetting and splitting, but still, it can
be a secondary choice to directly draw inside the empty annotation, which is
easier and faster for implementing (but less flexible and does not allow
splitting).
In following we show how to add a "complex version" of points annotation. The
only thing that needs to be careful is the location on x-axis (y-axis if it is
a row annotation) should correspond to the column index after column
reordering.
```{r, fig.width = 5.2}
# Note this example is only for demonstration of `anno_empty()`.
# Actually it can be made easily by `anno_points()`.
ha = HeatmapAnnotation(foo = anno_empty(border = TRUE, height = unit(3, "cm")))
ht = Heatmap(matrix(rnorm(100), nrow = 10), name = "mat", top_annotation = ha)
ht = draw(ht)
co = column_order(ht)
value = runif(10)
decorate_annotation("foo", {
# value on x-axis is always 1:ncol(mat)
x = 1:10
# while values on y-axis is the value after column reordering
value = value[co]
pushViewport(viewport(xscale = c(0.5, 10.5), yscale = c(0, 1)))
grid.lines(c(0.5, 10.5), c(0.5, 0.5), gp = gpar(lty = 2),
default.units = "native")
grid.points(x, value, pch = 16, size = unit(2, "mm"),
gp = gpar(col = ifelse(value > 0.5, "red", "blue")), default.units = "native")
grid.yaxis(at = c(0, 0.5, 1))
popViewport()
})
```
## Block annotation {#block-annotation}
There are two uses for block annotation. 1. simply as rectangles (with labels
inside) to mark heatmap slices, 2. as plotting regions to associate subsets of
rows or columns in the heatmap.
### Block for putting labels
In this case, the block annotation is more like a color block which identifies groups when
the rows or columns of the heatmap are split.
```{r, fig.width = 5.2}
Heatmap(matrix(rnorm(100), 10), name = "mat",
top_annotation = HeatmapAnnotation(foo = anno_block(gp = gpar(fill = 2:4))),
column_km = 3)
```
Labels can be added to each block.
```{r, fig.width = 5.2}
Heatmap(matrix(rnorm(100), 10), name = "mat",
top_annotation = HeatmapAnnotation(foo = anno_block(gp = gpar(fill = 2:4),
labels = c("group1", "group2", "group3"),
labels_gp = gpar(col = "white", fontsize = 10))),
column_km = 3,
left_annotation = rowAnnotation(foo = anno_block(gp = gpar(fill = 2:4),
labels = c("group1", "group2", "group3"),
labels_gp = gpar(col = "white", fontsize = 10))),
row_km = 3)
```
Note the length of `labels` or graphics parameters should have the same length
as the number of slices.
`anno_block()` function draws rectangles for row/column slices where one
rectangle only corresponds to one single slice. Then what if we want to draw
the rectangles over several slices to show they belong to certain groups?
Currently, it is difficult to directly support it in `anno_block()`, however,
there is workaround for it. Actually, to draw rectangles across several
slices, we need to know two things: 1. the positions of the slices in the
plot, and 2. space to draw the rectangles. Luckily, the positions can be
obtained by directly go to the correspoding viewport and the space can be
allocated by `anno_empty()` function.
In the following code, we use `anno_empty()` to create an empty annotation:
```{r, fig.width = 5.2}
set.seed(123)
mat2 = matrix(rnorm(50*50), nrow = 50)
split = rep(1:5, each = 10)
ha = HeatmapAnnotation(
empty = anno_empty(border = FALSE),
foo = anno_block(gp = gpar(fill = 2:6), labels = LETTERS[1:5])
)
Heatmap(mat2, name = "mat2", column_split = split, top_annotation = ha,
column_title = NULL)
```
Let's say, we want to put the first three column slices as a group and the last two
slices as the second group.
The positions of the first and the third slices for annotation `"empty"` can be obtained by:
```{r, eval = FALSE}
seekViewport("annotation_empty_1")
loc1 = deviceLoc(x = unit(0, "npc"), y = unit(0, "npc"))
seekViewport("annotation_empty_3")
loc2 = deviceLoc(x = unit(1, "npc"), y = unit(1, "npc"))
loc2
```
```{r, echo = FALSE, fig.width = 5.2}
pdf(NULL)
ha = HeatmapAnnotation(
empty = anno_empty(border = FALSE),
foo = anno_block(gp = gpar(fill = 2:6), labels = LETTERS[1:5])
)
Heatmap(mat2, name = "mat2", column_split = split, top_annotation = ha,
column_title = NULL)
seekViewport("annotation_empty_1")
loc1 = deviceLoc(x = unit(0, "npc"), y = unit(0, "npc"))
seekViewport("annotation_empty_3")
loc2 = deviceLoc(x = unit(1, "npc"), y = unit(1, "npc"))
invisible(dev.off())
loc2
```
The viewport name `"annotation_empty_1"` correspond to the first slice for
annotation `empty`, and we take the left bottom of the first "empty"
annotation slice and the top right of the third slice, saved in `loc1` and
`loc2` variables.
Here what is important is the use of `grid::deviceLoc()` function. It directly
converts a location measured in a certain viewport to the position in
the graphics device.
In the end, we go to the `"global"` viewport because the size of `"global"`
viewport is the size of the graphics device, and draw the rectangle and add
label.
```{r, eval = FALSE}
seekViewport("global")
grid.rect(loc1$x, loc1$y, width = loc2$x - loc1$x, height = loc2$y - loc1$y,
just = c("left", "bottom"), gp = gpar(fill = "red"))
grid.text("group 1", x = (loc1$x + loc2$x)*0.5, y = (loc1$y + loc2$y)*0.5)
```
```{r, echo = FALSE, fig.width = 5.2}
ha = HeatmapAnnotation(
empty = anno_empty(border = FALSE),
foo = anno_block(gp = gpar(fill = 2:6), labels = LETTERS[1:5])
)
Heatmap(mat2, name = "mat2", column_split = split, top_annotation = ha,
column_title = NULL)
seekViewport("annotation_empty_1")
loc1 = deviceLoc(x = unit(0, "npc"), y = unit(0, "npc"))
seekViewport("annotation_empty_3")
loc2 = deviceLoc(x = unit(1, "npc"), y = unit(1, "npc"))
seekViewport("global")
grid.rect(loc1$x, loc1$y, width = loc2$x - loc1$x, height = loc2$y - loc1$y,
just = c("left", "bottom"), gp = gpar(fill = "red"))
grid.text("group 1", x = (loc1$x + loc2$x)*0.5, y = (loc1$y + loc2$y)*0.5)
```
The viewport names for the annotations are in a fixed format, which is
`annotation_{annotation_name}_{slice_index}`. The full set of viewport names
can be obtained by `list_components()` function.
```{r, eval = FALSE}
list_components()
```
```{r, echo = FALSE, fig.width = 5.2}
pdf(NULL)
ha = HeatmapAnnotation(
empty = anno_empty(border = FALSE),
foo = anno_block(gp = gpar(fill = 2:6), labels = LETTERS[1:5])
)
Heatmap(mat2, name = "mat2", column_split = split, top_annotation = ha,
column_title = NULL)
list_components()
invisible(dev.off())
```
If more than one group-level rectangles are to be added, we can wrap the code
into a simple function `group_block_anno()`:
```{r, fig.width = 5.2}
ha = HeatmapAnnotation(
empty = anno_empty(border = FALSE, height = unit(8, "mm")),
foo = anno_block(gp = gpar(fill = 2:6), labels = LETTERS[1:5])
)
Heatmap(mat2, name = "mat2", column_split = split, top_annotation = ha,
column_title = NULL)
library(GetoptLong) # for the function qq()
group_block_anno = function(group, empty_anno, gp = gpar(),
label = NULL, label_gp = gpar()) {
seekViewport(qq("annotation_@{empty_anno}_@{min(group)}"))
loc1 = deviceLoc(x = unit(0, "npc"), y = unit(0, "npc"))
seekViewport(qq("annotation_@{empty_anno}_@{max(group)}"))
loc2 = deviceLoc(x = unit(1, "npc"), y = unit(1, "npc"))
seekViewport("global")
grid.rect(loc1$x, loc1$y, width = loc2$x - loc1$x, height = loc2$y - loc1$y,
just = c("left", "bottom"), gp = gp)
if(!is.null(label)) {
grid.text(label, x = (loc1$x + loc2$x)*0.5, y = (loc1$y + loc2$y)*0.5, gp = label_gp)
}
}
group_block_anno(1:3, "empty", gp = gpar(fill = "red"), label = "group 1")
group_block_anno(4:5, "empty", gp = gpar(fill = "blue"), label = "group 2")
```
### Blocks as plotting regions
When heatmap is split, each block in block annotation can be thought as a
virtual plotting region. `anno_block()` allows an argument `panel_fun` which
accepts a self-defined function that draws graphics in each slice. It must
have two arguments:
1. row/column indices for the current slice (let's call it `index`),
2. a vector of levels from the split variable that correspond to current slice (let's call it `level`). When e.g. `row_km` is
only set or `row_split` is only set to one categorical variable, then `level` is a vector of length one. If there are multiple
categorical variables set with `row_km` and `row_split`, `level` is a vector of which the length is the same as the number
of categorical variables.
When `panel_fun` is set, all other graphics parameters in `anno_block()` are ignored. See the following example:
```{r, fig.width = 7}
col = c("1" = "red", "2" = "blue", "A" = "green", "B" = "orange")
Heatmap(matrix(rnorm(100), 10), name = "mat", row_km = 2,
row_split = sample(c("A", "B"), 10, replace = TRUE)) +
rowAnnotation(foo = anno_block(
panel_fun = function(index, levels) {
grid.rect(gp = gpar(fill = col[levels[2]], col = "black"))
txt = paste(levels, collapse = ",")
txt = paste0(txt, "\n", length(index), " rows")
grid.text(txt, 0.5, 0.5, rot = 0,
gp = gpar(col = col[levels[1]]))
},
width = unit(3, "cm")
))
```
To make it more general, `anno_block()` accepts an argument `align_to` which defines
a list of indices that blocks will be corresponded to, but you need to make sure
the indices are continuously adjacent on heatmaps.
```{r, fig.width = 5.2}
split = sample(c("A", "B"), 10, replace = TRUE)
align_to = list("A" = which(split == "A"))
panel_fun = function(index, nm) {
grid.rect()
grid.text(paste0(length(index), " rows"), 0.5, 0.5)
}
Heatmap(matrix(rnorm(100), 10), name = "mat", row_split = split) +
rowAnnotation(foo = anno_block(
align_to = align_to,
panel_fun = panel_fun,
width = unit(3, "cm")
))
```
`anno_block()` normally works with `row_split`, but it is not necessary, see the following example:
```{r, fig.width = 5.2}
align_to = list("A" = 2:4, "B" = 7:9)
Heatmap(matrix(rnorm(100), 10), name = "mat", cluster_rows = FALSE) +
rowAnnotation(foo = anno_block(
align_to = align_to,
panel_fun = panel_fun,
width = unit(3, "cm")
))
```
## Image annotation {#image-annotation}
Images can be added as annotations. `anno_image()` supports image in `png`,
`svg`, `pdf`, `eps`, `jpeg/jpg`, `tiff` formats. How they are imported as
annotations are as follows:
- `png`, `jpeg/jpg` and `tiff` images are imported by `png::readPNG()`,
`jpeg::readJPEG()` and `tiff::readTIFF()`, and drawn by
`grid::grid.raster()`.
- `svg` images are firstly reformatted by `rsvg::rsvg_svg()` and then imported
by `grImport2::readPicture()` and drawn by `grImport2::grid.picture()`.
- `pdf` and `eps` images are imported by `grImport::PostScriptTrace()` and
`grImport::readPicture()`, later drawn by `grImport::grid.picture()`.
The free icons for following examples are from
https://github.com/Keyamoon/IcoMoon-Free. A vector of image paths are set as
the first argument of `anno_image()`.
```{r}
image_png = sample(dir("IcoMoon-Free-master/PNG/64px", full.names = TRUE), 10)
image_svg = sample(dir("IcoMoon-Free-master/SVG/", full.names = TRUE), 10)
image_eps = sample(dir("IcoMoon-Free-master/EPS/", full.names = TRUE), 10)
image_pdf = sample(dir("IcoMoon-Free-master/PDF/", full.names = TRUE), 10)
# we only draw the image annotation for PNG images, while the others are the same
ha = HeatmapAnnotation(foo = anno_image(image_png))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Different image formats can be mixed in the input vector.
```{r, eval = FALSE}
# code only for demonstration
ha = HeatmapAnnotation(foo = anno_image(c(image_png[1:3], image_svg[1:3],
image_eps[1:3], image_pdf[1:3])))
```
Border and background colors (if the images have transparent background) can
be set by `gp`.
```{r}
ha = HeatmapAnnotation(foo = anno_image(image_png,
gp = gpar(fill = 1:10, col = "black")))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
`border` controls the border of the whole annotation.
```{r}
ha = HeatmapAnnotation(foo = anno_image(image_png, border = "red"))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
Padding or space around the images is set by `space`.
```{r}
ha = HeatmapAnnotation(foo = anno_image(image_png, space = unit(3, "mm")))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
If only some of the images need to be drawn, the other elements in the `image`
vector can be set to `''` or `NA`.
```{r}
image_png[1:2] = ""
ha = HeatmapAnnotation(foo = anno_image(image_png))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
## Points annotation {#points-annotation}
Points annotation implemented by `anno_points()` shows distribution of a list
of data points. The data points object `x` can be a single vector or a matrix.
If it is a matrix, the graphics settings such as `pch`, `size` and `gp` can
correpspond to matrix columns. Note again, if `x` is a matrix, rows in `x`
correspond to columns in the heatmap matrix.
```{r}
ha = HeatmapAnnotation(foo = anno_points(runif(10)))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
```{r}
ha = HeatmapAnnotation(foo = anno_points(matrix(runif(20), nc = 2),
pch = 1:2, gp = gpar(col = 2:3)))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
`ylim` controls the range on "y-axis" or the "data axis" (if it is a row
annotation, the data axis is horizontal), `extend` controls the extended space
on the data axis direction. `axis` controls whether to show the axis and
`axis_param` controls the settings for axis. The default settings for axis are:
```{r}
default_axis_param("column")
```
And you can overwrite some of them:
```{r}
ha = HeatmapAnnotation(foo = anno_points(runif(10), ylim = c(0, 1),
axis_param = list(
side = "right",
at = c(0, 0.5, 1),
labels = c("zero", "half", "one")
))
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
One thing that might be useful is you can control the rotation of the axis
labels.
```{r}
ha = rowAnnotation(foo = anno_points(runif(10), ylim = c(0, 1),
width = unit(2, "cm"),
axis_param = list(
side = "bottom",
at = c(0, 0.5, 1),
labels = c("zero", "half", "one"),
labels_rot = 45
))
)
```
```{r, echo = FALSE, fig.width = annotation_width(ha)*1.2, fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
**The configuration of axis is same for all other annotation functions which have
axes.**
The default size of the points annotation is 5mm. It can be controlled by
`height`/`width` argument in `anno_points()`.
```{r}
ha = HeatmapAnnotation(foo = anno_points(runif(10), height = unit(2, "cm")))
```
```{r, echo = FALSE, fig.width = annotation_width(ha), fig.height = annotation_height(ha)}
draw(ha, test = TRUE)
```
## Line annotation {#lines-annotation}
`anno_lines()` connects the data points by a list of segments. Similar as
`anno_points()`, the data variable can be a numeric vector:
```{r}
ha = HeatmapAnnotation(foo = anno_lines(runif(10)))
```