forked from jokergoo/circlize_book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-graphics.Rmd
866 lines (722 loc) · 38 KB
/
03-graphics.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
# Graphics {#graphics}
In this chapter, we will introduce low-level functions that add graphics to
the circle. Usages of most of these functions are similar as normal graphic
functions (e.g. `points()`, `lines()`). Combination use of these functions can
generate very complex circular plots.
All low-level functions accept `sector.index` and `track.index` arguments
which indicate which cell the graphics are added in. By default the graphics
are added in the "current" sector and "current" track, so it is recommended to
use them directly inside `panel.fun` function. However, they can also be used
in other places with explicitly specifying sector and track index. Following
code shows an example of using `ciros.points()`.
```{r, eval = FALSE}
circos.track(..., panel.fun = function(x, y) {
circos.points(x, y)
})
circos.points(x, y, sector.index, track.index)
```
In this chapter, we will also discuss how to customize links and how to highlight
regions in the circle.
## Setting colors
Color is a major aesthetic element to map to the data points. In **circliez** there are
two functions that provides customization of colors.
`colorRamp2()` provides an exact way for mapping continuous values. users specify a vector
of break values and a vector of colors, all the other colors are linearly interpolated between
the correspoding break values. In following example, we generate a color mapping which is symmetric
to zero.
```{r}
col_fun = colorRamp2(c(-2, 0, 2), c("blue", "white", "red"))
col_fun(seq(-5, 1, by = 1)) # all the values smaller than -2 are all mapped to blue
```
`rand_color()` implements the algorithem of [randomColor.js](https://github.com/davidmerfield/randomColor).
See the following example:
```{r, fig.width = 6, fig.height = 5.4}
par(mar = c(1, 1, 1, 1))
plot(NULL, xlim = c(1, 10), ylim = c(1, 8), axes = FALSE, ann = FALSE)
points(1:10, rep(1, 10), pch = 16, cex = 5,
col = rand_color(10, luminosity = "random"))
points(1:10, rep(2, 10), pch = 16, cex = 5,
col = rand_color(10, luminosity = "bright"))
points(1:10, rep(3, 10), pch = 16, cex = 5,
col = rand_color(10, luminosity = "light"))
points(1:10, rep(4, 10), pch = 16, cex = 5,
col = rand_color(10, luminosity = "dark"))
points(1:10, rep(5, 10), pch = 16, cex = 5,
col = rand_color(10, hue = "red", luminosity = "bright"))
points(1:10, rep(6, 10), pch = 16, cex = 5,
col = rand_color(10, hue = "green", luminosity = "bright"))
points(1:10, rep(7, 10), pch = 16, cex = 5,
col = rand_color(10, hue = "blue", luminosity = "bright"))
points(1:10, rep(8, 10), pch = 16, cex = 5,
col = rand_color(10, hue = "monochrome", luminosity = "bright"))
```
## Points {#points}
Adding points by `circos.points()` is similar as `points()` function. Possible
usage is:
```{r, eval = FALSE}
circos.points(x, y)
circos.points(x, y, sector.index, track.index)
circos.points(x, y, pch, col, cex)
```
There is a companion function `circos.trackPoints()` which adds points to all
sectors in a same track simultaneously. The input of `circos.trackPoints()`
must contain a vector of categorical factors, a vector of x values and a
vector of y values. X values and y values are split by the categorical
variable and corresponding subset of x and y values are internally sent to
`circos.points()`. `circos.trackPoints()` adds points to the "current" track
by default which is the most recently created track. Other tracks can also be
selected by explictly setting `track.index` argument.
```{r, eval = FALSE}
circos.track(...)
circos.trackPoints(fa, x, y)
```
`circos.trackPoints()` is simply implemented by `circos.points()` with a `for`
loop. However, it is more recommended to directly use `circos.points()` and
`panel.fun` which provides great more flexibility. Actually following code is
identical to above code.
```{r, eval = FALSE}
circos.track(fa, x, y, panel.fun = function(x, y) {
circos.points(x, y)
})
```
Other low-level functions also have their companion `circos.track*()`
function. The usage is same as `circos.trackPoints()` and they will not be
further discussed in following sections.
## Lines {#lines}
Adding lines by `circos.lines()` is similar as `lines()` function. One
additional feature is that the areas under or above the lines can be filled by
specifing `area` argument to `TRUE`. Position of the baseline can be set to a
pre-defined string of `bottom` or `top`, or a numeric value which is the
position on y-axis. When `area` is set to `TRUE`, `col` controls the filled
color and `border` controls the color for the borders.
`baseline` argument is also workable when `lty` is set to `"h"`. Note when `lty`
is set to `"h"`, graphic parameters such as `col` can be set as a vector with
same length as `x`. Figure \@ref(fig:circlize-lines) illustrates supported `lty`
settings and `area`/`baseline` settings.
```{r circlize-lines, echo = FALSE, fig.width = 6, fig.height = 6, fig.cap = "Line styles and areas supported in `circos.lines()`"}
source("src/intro-08-lines.R")
```
Straight lines are transformed to curves when mapping to the circular layout
(Figure \@ref(fig:circlize-linecurve)). Normally, curves are approximated by a
series of segments of straight lines. With more and shorter segments, there is
better approximation, but with larger size if the figures are generated into
e.g. PDF files, especially for huge dataset. Default length of segments in
**circlize** is a balance between the quality and size of the figure. You can
set the length of the unit segment by `unit.circle.segments` option in
`circos.par()`. The length of the segment is calculated as the length of the
unit circle (2$\pi$) divided by `unit.circle.segments`. In some scenarios,
actually you don't need to segment the lines such as radical lines, then you can
set `straight` argument to `TRUE` to get rid of unnecessary segmentations.
```{r circlize-linecurve, echo = FALSE, fig.width = 8, fig.height = 2, fig.cap = "Transformation of straight lines into curves in the circle."}
source("src/intro-08-linescurve.R")
```
Possible usage for `circos.lines()` is:
```{r, eval = FALSE}
circos.lines(x, y)
circos.lines(x, y, sector.index, track.index)
circos.lines(x, y, col, lwd, lty, type, straight)
circos.lines(x, y, col, area, baseline, border)
```
## Segments {#segments}
Line segments can be added by `circos.segments()` function. The usage is similar
as `segments()`. Radical segments can be added by setting `straight` to `TRUE`.
An example is in Figure \@ref(fig:circlize-segments).
```{r, eval = FALSE}
circos.segments(x0, y0, x1, y1)
circos.segments(x0, y0, x1, y1, straight)
```
```{r circlize-segments, echo = FALSE, fig.cap = "Draw segments."}
circos.initialize(letters[1:8], xlim = c(0, 1))
circos.track(ylim = c(0, 1), track.height = 0.3, panel.fun = function(x, y) {
x = seq(0.2, 0.8, by = 0.2)
y = seq(0.2, 0.8, by = 0.2)
circos.segments(x, 0.1, x, 0.9)
circos.segments(0.1, y, 0.9, y)
})
circos.clear()
```
## Text {#text}
Adding text by `circos.text()` is similar as `text()` function. Text is added on
the plot for human reading, thus, when putting the text on the circle, the
facing of text is very important. `circos.text()` supports seven facing options
which are `inside`, `outside`, `clockwise`, `reverse.clockwise`, `downward`,
`bending.inside` and `bending.outside`. Please note for `bending.inside` and
`bending.outside`, currently, single line text is only supported. If you want to
put bended text into two lines, you need to split text into two lines and add
each line by `circos.text()` separately. The different facings are illustrated
in Figure \@ref(fig:circlize-text).
```{r circlize-text, echo = FALSE, fig.cap = "Text facings."}
source("src/intro-09-text.R")
```
Possible usage for `circos.text()` is:
```{r, eval = FALSE}
circos.text(x, y, labels)
circos.text(x, y, labels, sector.index, track.index)
circos.text(x, y, labels, facing, niceFacing, adj, cex, col, font)
```
If, e.g., `facing` is set to `inside`, text which is on the bottom half of the
circle is still facing to the top and hard to read. To make text more easy to
read and not to hurt readers' neck too much, `circos.text()` provides
`niceFacing` option which automatically adjust text facing according to their
positions in the circle. `niceFacing` only works for `facing` value of
`inside`, `outside`, `clockwise`, `reverse.clockwise`, `bending.inside` and
`bending.outside`.
When `niceFacing` is on, `adj` is also adjusted according to the corresponding
facings. Figure \@ref(fig:circlize-text-easy) illustrates text positions under
different settings of `adj` and `facing`. The red dots are the positions of the texts.
```{r circlize-text-easy, echo = FALSE, fig.width = 8, fig.height = 8*3/2, fig.cap = "Human easy text facing."}
source("src/intro-09-text-niceFacing.R")
```
`adj` is internally passed to `text()`, thus, it actually adjusts text
positions either horizontally or vertically (in the canvas coordinate). If the
direction of the offset is circular, the offset value can be set as degrees
that the position of the text is adjusted by wrapping the offset by
`degree()`.
```{r, eval = FALSE}
circos.text(x, y, labels, adj = c(0, degree(5)), facing = "clockwise")
```
As `circos.text()` is applied in the data coordiante, offset can be directly
added to `x` or/and `y` as a value measured in the data coordinate. An absolute
offset can be set by using e.g. `mm_x()` (in x direction) and `mm_y()` (in y
direction).
```{r, eval = FALSE}
circos.text(x + mm_x(2), y + mm_y(2), labels)
```
## Rectangles and polygons {#rectangles}
Theoretically, circular rectangles and polygons are all polygons. If you imagine
the plotting region in a cell as Cartesian coordinate, then `circos.rect()`
draws rectangles. In the circle, the up and bottom edge become two arcs. Note this
function can be vectorized.
```{r, eval = FALSE}
circos.rect(xleft, ybottom, xright, ytop)
circos.rect(xleft, ybottom, xright, ytop, sector.index, track.index)
circos.rect(xleft, ybottom, xright, ytop, col, border, lty, lwd)
```
`circos.polygon()` draws a polygon through a series of points in a cell.
Please note the first data point must overlap to the last data point.
```{r, eval = FALSE}
circos.polygon(x, y)
circos.polygon(x, y, col, border, lty, lwd)
```
In Figure \@ref(fig:circlize-errorline), the area of standard deviation of the
smoothed line is drawn by `circos.polygon()`. Source code can be found in the
**Examples** section of the `circos.polygon()` help page.
```{r circlize-errorline, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Area of standard deviation of the smoothed line."}
source("src/intro-10-smooth.R")
```
## Axes {#axes}
Mostly, we only draw x-axes on the circle. `circos.axis()` or `circos.xaxis()`
privides options to customize x-axes which are on the circular direction. It
supports basic functionalities as `axis()` such as defining the breaks and
corresponding labels. Besides that, the function also supports to put x-axes to
a specified position on y direction, to position the x-axes facing the center of
the circle or outside of the circle, and to customize the axes ticks. The `at`
and `labels` arguments can be set to a long vector that the parts which exceed
the maximal value in the corresponding cell are removed automatically. The
facing of labels text can be optimized by `labels.niceFacing` (by default it is
`TRUE`).
Figure \@ref(fig:circlize-xaxis) illustrates different settings of x-axes. The
explanations are as follows:
- a: Major ticks are calculated automatically, other settings are defaults.
- b: Ticks are pointing to inside of the circle, facing of tick labels is set to
`outside`.
- c: Position of x-axis is `bottom` in the cell.
- d: Ticks are pointing to the inside of the circle, facing of tick labels is
set to `reverse.clockwise`.
- e: manually set major ticks and also set the position of x-axis.
- f: replace numeric labels to characters, with no minor ticks.
- g: No ticks for both major and minor, facing of tick labels is set to
`reverse.clockwise`.
- h: Number of minor ticks between two major ticks is set to 2. Length of ticks
is longer. Facing of tick labels is set to `clockwise`.
```{r circlize-xaxis, echo = FALSE, fig.cap = "X-axes"}
source("src/intro-11-axis.R")
```
As you may notice in the above figure, when the first and last axis labels
exceed data ranges on x-axis in the corresponding cell, their positions are
automatically adjusted to be shifted inwards in the cell.
Possible usage of `circos.axis()` is as follows. Note `h` can be `bottom`, `top`
or a numeric value.
```{r, eval = FALSE}
circos.axis(h)
circos.axis(h, sector.index, track.index)
circos.axis(h, major.at, labels, major.tick, direction)
circos.axis(h, major.at, labels, major.tick, labels.font, labels.cex,
labels.facing, labels.niceFacing)
circos.axis(h, major.at, labels, major.tick, minor.ticks,
major.tick.length, lwd)
```
Y-axis is also supported by `circos.yaxis()`. The usage is similar as
`circos.axis()` One thing that needs to be note is users need to manually adjust
`gap.degree`/`gap.after` in `circos.par()` to make sure there are enough spaces for y-axes.
(Figure \@ref(fig:circlize-yaxis))
```{r, eval = FALSE}
circos.yaxis(side)
circos.yaxis(at, labels, sector.index, track.index)
```
```{r circlize-yaxis, echo = FALSE, fig.cap = "Y-axes"}
source("src/intro-11-yaxis.R")
```
## Barplots, boxplots and violin plots
`circos.barplot()`, `circos.boxplot()` and `circos.violin()` are introduced
together because the values on x-axes are the integer indices of bars, boxes
or violins for which xlim should be properly set in `circos.initialize()`.
For circular barplots, users can either specify a vector which generates a
“normal” barplot, or a matrix which generates a stacked barplot (Figure \@ref(fig:circlize-barplot)).
```{r circlize-barplot, echo = FALSE, fig.width = 8, fig.height = 4, fig.cap = "Circular barplots."}
par(mfrow = c(1, 2))
circos.initialize(fa = letters[1:4], xlim = c(0, 10))
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
value = runif(10)
circos.barplot(value, 1:10 - 0.5, col = 1:10)
})
circos.track(ylim = c(-1, 1), panel.fun = function(x, y) {
value = runif(10, min = -1, max = 1)
circos.barplot(value, 1:10 - 0.5, col = ifelse(value > 0, 2, 3))
})
circos.clear()
circos.initialize(fa = letters[1:4], xlim = c(0, 10))
circos.track(ylim = c(0, 4), panel.fun = function(x, y) {
value = matrix(runif(10*4), ncol = 4)
circos.barplot(value, 1:10 - 0.5, col = 2:5)
})
circos.clear()
```
For circular boxplots, the boxes can be drawn one-by-one by providing a vector
for each box, or drawn in batch with a list/matrix as input (Figure \@ref(fig:circlize-boxplot)).
```{r circlize-boxplot, echo = FALSE, fig.width = 8, fig.height = 4, fig.cap = "Circular boxplots."}
par(mfrow = c(1, 2))
circos.initialize(fa = letters[1:4], xlim = c(0, 10))
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
for(pos in seq(0.5, 9.5, by = 1)) {
value = runif(10)
circos.boxplot(value, pos)
}
})
circos.clear()
circos.initialize(fa = letters[1:4], xlim = c(0, 10))
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
value = replicate(runif(10), n = 10, simplify = FALSE)
circos.boxplot(value, 1:10 - 0.5, col = 1:10)
})
circos.clear()
```
For circular violin plots, the violins can be drawn one-by-one by providing a vector for each violin, or drawn in batch with a list/matrix as input (Figure \@ref(fig:circlize-violinplot)).
Please note, to make it comparable between violins, `max_density` argument should be set.
```{r circlize-violinplot, echo = FALSE, fig.width = 8, fig.height = 4, fig.cap = "Circular violin plots."}
par(mfrow = c(1, 2))
circos.initialize(fa = letters[1:4], xlim = c(0, 10))
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
for(pos in seq(0.5, 9.5, by = 1)) {
value = runif(10)
circos.violin(value, pos)
}
})
circos.clear()
circos.initialize(fa = letters[1:4], xlim = c(0, 10))
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
value = replicate(runif(10), n = 10, simplify = FALSE)
circos.violin(value, 1:10 - 0.5, col = 1:10)
})
circos.clear()
```
## Circular arrows
Circular arrows can be used to represent stages in a circle. `circos.arrow()`
draws circular arrows parallel to the circle. Since the arrow is always
parallel to the circle, on x-direction, the start and end position of the
arrow need to be defined while on the y-direction, only the position of the
center of arrow needs to be defined. Also `width` controls the width of the
arrow and the length is defined by `x2 - x1`. `arrow.head.width` and
`arrow.head.length` control the size of the arrow head, and values are
measured in the data coordinate in corresponding cell. `tail` controls the
shape of the arrow tail. Note for `width`, `arrow.head.width` and
`arrow.head.length`, the value can be set by e.g. `mm_x()`, `mm_y()` with absolute
units. If users want to draw the arrows in the reversed direction, set `arrow.position`
argument to `start`. See Figure \@ref(fig:circular-arrow).
```{r circular-arrow, fig.width = 8, fig.height = 4, fig.cap = "Circular arrows."}
par(mfrow = c(1, 2))
circos.initialize(letters[1:4], xlim = c(0, 1))
col = rand_color(4)
tail = c("point", "normal", "point", "normal")
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
circos.arrow(x1 = 0, x2 = 1, y = 0.5, width = 0.4,
arrow.head.width = 0.6, arrow.head.length = cm_x(1),
col = col[CELL_META$sector.numeric.index],
tail = tail[CELL_META$sector.numeric.index])
}, bg.border = NA, track.height = 0.4)
circos.clear()
circos.initialize(letters[1:4], xlim = c(0, 1))
tail = c("point", "normal", "point", "normal")
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
circos.arrow(x1 = 0, x2 = 1, y = 0.5, width = 0.4,
arrow.head.width = 0.6, arrow.head.length = cm_x(1),
col = col[CELL_META$sector.numeric.index],
tail = tail[CELL_META$sector.numeric.index],
arrow.position = "start")
}, bg.border = NA, track.height = 0.4)
circos.clear()
```
Circular arrows are useful to visualize events which happen in circular style,
such as different phases in cell cycle. Following example code visualizes four
phases in cell cycle where the width of sectors correspond to the hours in
each phase (Figure \@ref(fig:cell-cycle)). Also circular arrows can be used to
visualize genes in circular genome where the arrows represent the orientation
of the gene, such as [mitochondrial genome](https://en.wikipedia.org/wiki/Mitochondrial_DNA)
or [plasmid genome](https://en.wikipedia.org/wiki/Plasmid). Just remember if the gene
is in the reverse strand or the negative strand, set `arrow.position = "start"` to
draw the arrow in the other direction.
```{r cell-cycle, fig.width = 4, fig.height = 4, fig.cap = "Cell cycle."}
cell_cycle = data.frame(phase = factor(c("G1", "S", "G2", "M"), levels = c("G1", "S", "G2", "M")),
hour = c(11, 8, 4, 1))
color = c("#66C2A5", "#FC8D62", "#8DA0CB", "#E78AC3")
circos.par(start.degree = 90)
circos.initialize(cell_cycle$phase, xlim = cbind(rep(0, 4), cell_cycle$hour))
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
circos.arrow(CELL_META$xlim[1], CELL_META$xlim[2],
arrow.head.width = CELL_META$yrange*0.8, arrow.head.length = cm_x(0.5),
col = color[CELL_META$sector.numeric.index])
circos.text(CELL_META$xcenter, CELL_META$ycenter, CELL_META$sector.index,
facing = "downward")
circos.axis(h = 1, major.at = seq(0, round(CELL_META$xlim[2])), minor.ticks = 1,
labels.cex = 0.6)
}, bg.border = NA, track.height = 0.3)
circos.clear()
```
## Raster image {#raster-image}
`circos.raster()` is used to add a raster image at a certain position in the
circle with proper rotation. The first input variable should be a `raster`
object or an object that can be converted by `as.raster()`. Facing of the
image is controlled by `facing` and `niceFacing` arguments which are similar
as in `circos.text()`. When value of `facing` is one of `inside`, `outside`,
`reverse.clockwise`, `clockwise` and `downward`, the size of raster image
should have absolute values which should be specified in the form of `number-
unit` such as `"20mm"`, `"1.2cm"` or `"0.5inche"`. If only one of `width` and
`height` is specified, the other one is automatically calculated by using the
aspect ratio of the original image. Following example shows five types of
facings of the raster image (figure \@ref(fig:raster-normal)).
```{r raster-normal, fig.width = 4, fig.height = 4, fig.cap = "Five facings of raster image."}
library(png)
image = system.file("extdata", "Rlogo.png", package = "circlize")
image = as.raster(readPNG(image))
circos.par(start.degree = 90)
circos.initialize(letters[1:5], xlim = c(0, 1))
all_facing_options = c("inside", "outside", "reverse.clockwise", "clockwise", "downward")
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
circos.raster(image, CELL_META$xcenter, CELL_META$ycenter, width = "1cm",
facing = all_facing_options[CELL_META$sector.numeric.index])
circos.text(CELL_META$xcenter, CELL_META$ycenter,
all_facing_options[CELL_META$sector.numeric.index],
facing = "inside", niceFacing = TRUE)
})
circos.clear()
```
Also `facing` can be set to `bending.inside` and `bending.outside` that the
image is filled to a circular rectangle. The strategy is to plot each original
pixel as a small circular rectangle by `circos.rect()`, thus, the plotting is
quite slow. If the original image is too huge, `scaling` argument can be set
to reduce the size of the original image.
Following code draws the image of the cover of this book which is a circular
style of [Keith Haring](https://en.wikipedia.org/wiki/Keith_Haring)'s doodle
(Figure \@ref(fig:raster-doodle)). The original source of the plot is from
http://www.thegreenhead.com/imgs/keith-haring-double-retrospect-worlds-largest-jigsaw-puzzle-2.jpg.
```{r, eval = FALSE}
load(system.file("extdata", "doodle.RData", package = "circlize"))
circos.par("cell.padding" = c(0, 0, 0, 0))
circos.initialize(letters[1:16], xlim = c(0, 1))
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
img = img_list[[CELL_META$sector.numeric.index]]
circos.raster(img, CELL_META$xcenter, CELL_META$ycenter,
width = CELL_META$xrange, height = CELL_META$yrange,
facing = "bending.inside")
}, track.height = 0.25, bg.border = NA)
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
img = img_list[[CELL_META$sector.numeric.index + 16]]
circos.raster(img, CELL_META$xcenter, CELL_META$ycenter,
width = CELL_META$xrange, height = CELL_META$yrange,
facing = "bending.inside")
}, track.height = 0.25, bg.border = NA)
circos.clear()
```
```{r raster-doodle, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Fill raster image to the cell."}
knitr::include_graphics("images/doodle.jpeg")
```
## Links {#links}
Links or ribbons are important part for the circular visualization. They are
used to represent relations or interactions between sectors. In **circlize**,
`circos.link()` draws links between single points and intervals. There are
four mandatory arguments which are index for the first sector, positions on
the first sector, index for the second sector and positions on the second
sector. If the positions on the two sectors are all single points, the link
represents as a line. If the positions on the two sectors are intervals, the link
represents as a robbon (Figure \@ref(fig:link-example)). Possible usage for
`circos.link()` is as follows.
```{r, eval = FALSE}
circos.link(sector.index1, 0, sector.index2, 0)
circos.link(sector.index1, c(0, 1), sector.index2, 0)
circos.link(sector.index1, c(0, 1), sector.index2, c(1, 2))
circos.link(sector.index1, c(0, 1), sector.index2, 0, col, lwd, lty, border)
```
```{r link-example, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Different types of links."}
factors = letters[1:8]
circos.par(points.overflow.warning = FALSE)
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
circos.link("a", 5, "c", 5, border = 1)
circos.link("b", 5, "d", c(4, 6), border = 1)
circos.link("a", c(2, 3), "f", c(4, 6), border = 1)
circos.link("e", c(2, 3), "g", 5, border = 1)
circos.clear()
```
The position of link end is controlled by `rou` (sorry the name should be called `rho`). By default, it is the bottom
of the most inside track and normally, you don't need to care about
this setting. The two ends of the link are located in a same circle by default. The
positions of two ends can be adjusted with different values for `rou1` and
`rou2` arguments. See Figure \@ref(fig:link-end).
```{r, eval = FALSE}
circos.link(sector.index1, 0, sector.index2, 0, rou)
circos.link(sector.index1, 0, sector.index2, 0, rou1, rou2)
```
```{r link-end, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Positions of link ends."}
circos.par(points.overflow.warning = FALSE)
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
circos.link("a", 5, "c", 5, rou2 = 0.5, border = 1)
circos.link("b", 5, "d", c(4, 6), rou2 = 0.5, border = 1)
circos.link("a", c(2, 3), "f", c(4, 6), rou2 = 0.5, border = 1)
```
The height of the link is controlled by `h` argument. In most cases, you don't
need to care about the value of `h` because they are internally calculated
based on the width of each link. However, when the link represents as a ribbon
(i.e. link from point to interval or from interval to interval), It can not
always ensure that one border is always below or above the other, which means,
in some extreme cases, the two borders are intersected and the link would be
messed up. It happens especially when position of the two ends are too close
or the width of one end is extremely large while the width of the other end is
too small. In that case, users can manually set height of the top and bottom
border by `h` and `h2` (Figure \@ref(fig:link-height)).
```{r, eval = FALSE}
circos.link(sector.index1, 0, sector.index2, 0, h)
circos.link(sector.index1, 0, sector.index2, 0, h, h2)
```
```{r link-height, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Adjust link heights."}
circos.par(points.overflow.warning = FALSE)
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
circos.link("a", 10, "b", c(1, 9), border = 1);
circos.text(9, -8, "default `h`", adj = c(0, 0.5), sector.index = "a", facing = "downward")
circos.link("c", 10, "d", c(1, 9), h = 0.5, h2 = 0.2, border = 1)
circos.text(1, -3, "h = 0.5\nh2 = 0.2", adj = c(0, 0.5), sector.index = "e", facing = "downward")
circos.clear()
```
When there are many links, the height of all links can be systematically adjusted by `h.ratio` (Figure \@ref(fig:link-ratio)).
The value is between 0 and 1.
```{r link-ratio, echo = FALSE, fig.width = 8, fig.height = 8/3, fig.cap = "Adjust link heights by `h.ratio`."}
par(mfrow = c(1, 3))
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
for(i in 1:100) {
circos.link(sample(factors, 1), runif(1, max = 10), sample(factors, 1), runif(1, max = 10),
h.ratio = 0.7)
}
circos.clear()
text(-1, 1, "h.ratio = 0.7", adj = c(0, 1))
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
for(i in 1:100) {
circos.link(sample(factors, 1), runif(1, max = 10), sample(factors, 1), runif(1, max = 10),
h.ratio = 0.5)
}
circos.clear()
text(-1, 1, "h.ratio = 0.5\ndefault", adj = c(0, 1))
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
for(i in 1:100) {
circos.link(sample(factors, 1), runif(1, max = 10), sample(factors, 1), runif(1, max = 10),
h.ratio = 0.3)
}
circos.clear()
text(-1, 1, "h.ratio = 0.3", adj = c(0, 1))
```
The border of link (if it is a ribbon) or the link itself (if it is a line) is
in fact a quadratic Bezier curve, thus you can control the shape of the link
by `w` and `w2` (`w2` controls the shape of bottom border). See Figure
\@ref(fig:link-shape) for examples. For more explanation of `w`, please refer
to http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Rational_B.C3.A9zier_curves.
```{r, eval = FALSE}
circos.link(sector.index1, 0, sector.index2, 0, w)
circos.link(sector.index1, 0, sector.index2, 0, w, w2)
```
```{r link-shape, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Different link shapes."}
circos.par(points.overflow.warning = FALSE)
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
circos.link("a", 5, "b", 5); circos.text(10, -5, "default", facing = "outside", sector.index = "a")
circos.link("b", 5, "c", 5, h = 0.2); circos.text(10, -5, "h=0.2", facing = "outside", sector.index = "b")
circos.link("c", 5, "d", 5, h = 0.8); circos.text(10, -5, "h=0.8", facing = "outside", sector.index = "c")
circos.link("d", 5, "e", 5, w = 2); circos.text(10, -5, "w=2", facing = "downward", sector.index = "d")
circos.link("e", 5, "f", 5, w = -0.5); circos.text(10, 5, "w=-0.5", sector.index = "e")
circos.link("f", 5, "g", 5, w = 0.1, h = 0.3); circos.text(10, -5, "w=0.1\nh=0.3", sector.index = "f")
circos.clear()
```
When the links represent as ribbons and the two ends overlap, the links will
be de-generated as a 'hill' (Figure \@ref(fig:link-hill)).
```{r link-hill, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Link as a hill."}
circos.par(points.overflow.warning = FALSE)
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
circos.link("a", c(2, 6), "a", c(3, 7))
circos.clear()
```
Links can have arrows to represent the directions. The `directional` argument
controls how to add arrows. A value of `0` means there is no direction, `1`
means the direction is from end 1 to end 2, `-1` means the direction is from
end 2 to end 1, and `2` means bi-direction. If the link represents as a
ribbon, a line with arrow will be added in the center of the link to represent
directions. See Figure \@ref(fig:link-arrow).
Type of arrows is controlled by `arr.type` argument and it is actually passed
to `Arrowhead()` defined in **shape** package. Besides the arrow types
supported in **shape** package, there is an additional arrow type `big.arrow`
which turns the robbon into a big arrow (Figure \@ref(fig:link-arrow)).
Unequal height of the link ends can also represent directions which we will
discuss more with the `chordDiagram()` function.
```{r, eval = FALSE}
circos.link(sector.index1, 0, sector.index2, 0, directional = 1)
circos.link(sector.index1, c(0, 1), sector.index2, c(0, 1), directional = -1)
```
```{r link-arrow, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Link with arrows."}
circos.par(points.overflow.warning = FALSE)
circos.initialize(factors = factors, xlim = c(0, 10))
circos.track(factors = factors, ylim = c(0, 1), bg.col = "grey", bg.border = NA, track.height = 0.05)
circos.link("a", 5, "b", 5, directional = 1, arr.length = 0.2)
circos.link("c", c(3, 7), "d", c(3, 7), directional = 1, arr.col = "white", arr.length = 0.2)
circos.link("e", c(4, 6), "f", c(4, 6), directional = 1, arr.type = "big.arrow", arr.length = 0.04)
circos.clear()
```
## Highlight sectors and tracks {#highlight-sectors-and-tracks}
`draw.sector()` draws sectors, rings or their parts. This function is useful
if you want to highlight some parts of your circular plot. it needs arguments
of the position of circle center (by default `c(0, 0)`), the start degree and
the end degree for sectors, and radius for two edges (or one edge) which are
up or bottom borders. `draw.sector()` is independent from the circular plot.
Possible usage of `draw.sector()` is as follows.
```{r eval = FALSE}
draw.sector(start.degree, end.degree, rou1)
draw.sector(start.degree, end.degree, rou1, rou2, center)
draw.sector(start.degree, end.degree, rou1, rou2, center, col, border, lwd, lty)
```
Directions from `start.degree` and `end.degree` is important for drawing sectors.
By default, it is clock wise.
```{r eval = FALSE}
draw.sector(start.degree, end.degree, clock.wise = FALSE)
```
Following code shows examples of `draw.sector()` (Figure \@ref(fig:draw-sector-general)).
```{r draw-sector-general, fig.width = 4, fig.height = 4, fig.cap = "General usage of `draw.sector()`."}
par(mar = c(1, 1, 1, 1))
plot(c(-1, 1), c(-1, 1), type = "n", axes = FALSE, ann = FALSE, asp = 1)
draw.sector(20, 0)
draw.sector(30, 60, rou1 = 0.8, rou2 = 0.5, clock.wise = FALSE, col = "#FF000080")
draw.sector(350, 1000, col = "#00FF0080", border = NA)
draw.sector(0, 180, rou1 = 0.25, center = c(-0.5, 0.5), border = 2, lwd = 2, lty = 2)
draw.sector(0, 360, rou1 = 0.7, rou2 = 0.6, col = "#0000FF80")
```
In order to highlight cells in the circular plot, we can use
`get.cell.meta.data()` to get the information of positions of cells. E.g. the
start degree and end degree can be obtained through `cell.start.degree` and
`cell.end.degree`, and the position of the top border and bottom border can be
obtained through `cell.top.radius` and `cell.bottom.radius`. Following code
shows several examples to highlight sectors and tracks.
First we create a circular plot with eight sectors and three tracks.
```{r circlize_highlight_1, eval = FALSE}
factors = letters[1:8]
circos.initialize(factors, xlim = c(0, 1))
for(i in 1:3) {
circos.track(ylim = c(0, 1))
}
circos.info(plot = TRUE)
```
If we want to highlight sector a (Figure \@ref(fig:circlize-highlight)):
```{r circlize_highlight_2, eval = FALSE}
draw.sector(get.cell.meta.data("cell.start.degree", sector.index = "a"),
get.cell.meta.data("cell.end.degree", sector.index = "a"),
rou1 = get.cell.meta.data("cell.top.radius", track.index = 1),
col = "#FF000040")
```
If we want to highlight track 1 (Figure \@ref(fig:circlize-highlight)):
```{r circlize_highlight_3, eval = FALSE}
draw.sector(0, 360,
rou1 = get.cell.meta.data("cell.top.radius", track.index = 1),
rou2 = get.cell.meta.data("cell.bottom.radius", track.index = 1),
col = "#00FF0040")
```
If we want to highlight track 2 and 3 in sector e and f (Figure \@ref(fig:circlize-highlight)):
```{r circlize_highlight_4, eval = FALSE}
draw.sector(get.cell.meta.data("cell.start.degree", sector.index = "e"),
get.cell.meta.data("cell.end.degree", sector.index = "f"),
rou1 = get.cell.meta.data("cell.top.radius", track.index = 2),
rou2 = get.cell.meta.data("cell.bottom.radius", track.index = 3),
col = "#0000FF40")
```
If we want to highlight specific regions such as a small region inside cell
`h:2`, we can use `circlize()` to calculate the positions in the polar
coordinate. But always keep in mind that x-axis in the cell are always clock
wise. See Figure \@ref(fig:circlize-highlight).
```{r circlize_highlight_5, eval = FALSE}
pos = circlize(c(0.2, 0.8), c(0.2, 0.8), sector.index = "h", track.index = 2)
draw.sector(pos[1, "theta"], pos[2, "theta"], pos[1, "rou"], pos[2, "rou"],
clock.wise = TRUE, col = "#00FFFF40")
circos.clear()
```
```{r circlize-highlight, echo = FALSE, fig.width = 4, fig.height = 4, fig.cap = "Highlight sectors and tracks."}
chunks <- knitr:::knit_code$get()
eval(parse(text = chunks[["circlize_highlight_1"]]))
eval(parse(text = chunks[["circlize_highlight_2"]]))
eval(parse(text = chunks[["circlize_highlight_3"]]))
eval(parse(text = chunks[["circlize_highlight_4"]]))
eval(parse(text = chunks[["circlize_highlight_5"]]))
```
If the purpose is to simply highlight complete cells, there is a helper
function `highlight.sector()` for which you only need to specify index for
sectors and tracks that you want to to highlight. Paddings of the highligted
regions can be set by `padding` argument which should contain four values
representing ratios of the width or height of the highlighted region (Figure \@ref(fig:circlize-highlight-sector)).
One advantage of `highlight.sector()` is that it supports to add text in the
highlighted regions. By default, the text is drawn at that center of the
highlighted region. The position on the radical direction can be set by
`text.vjust` argument either by a numeric value or a string in form of `"2 inches"`` or `"-1.2cm"`.
```{r circlize-highlight-sector, fig.width = 4, fig.height = 4, fig.cap = "Highlight sectors."}
factors = letters[1:8]
circos.initialize(factors, xlim = c(0, 1))
for(i in 1:4) {
circos.track(ylim = c(0, 1))
}
circos.info(plot = TRUE)
highlight.sector(c("a", "h"), track.index = 1, text = "a and h belong to a same group",
facing = "bending.inside", niceFacing = TRUE, text.vjust = "6mm", cex = 0.8)
highlight.sector("c", col = "#00FF0040")
highlight.sector("d", col = NA, border = "red", lwd = 2)
highlight.sector("e", col = "#0000FF40", track.index = c(2, 3))
highlight.sector(c("f", "g"), col = NA, border = "green",
lwd = 2, track.index = c(2, 3), padding = c(0.1, 0.1, 0.1, 0.1))
highlight.sector(factors, col = "#FFFF0040", track.index = 4)
circos.clear()
```
## Work together with the base graphic system {#work-with-base-graphic-system}
**circlize** is built on the base R graphic system, then, of course the base graphic
functions can be used in combination with circlize functions. On the other hand,
`circlize()` converts data points from the data coordinates to the canvas coordinates
where the base graphic function can be directly applied.
Normally, the base functions such as `title()`, `text()`, `legend()` can be used to
add extra information on the plot (Figure \@ref(fig:circlize-base)).
Sometimes, when the text or other graphics are far from the circle, you may set `par(xpd = NA)`
so that the plotting is not clipped.
```{r circlize-base, fig.cap = "Work with base graphic functions."}
factors = letters[1:4]
circos.initialize(factors = factors, xlim = c(0, 1))
circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
circos.points(1:20/20, 1:20/20)
})
text(0, 0, "This is\nthe center", cex = 1.5)
legend("bottomleft", pch = 1, legend = "This is the legend")
title("This is the title")
circos.clear()
```