-
Notifications
You must be signed in to change notification settings - Fork 50
/
A-app-faq.Rmd
666 lines (425 loc) · 26.9 KB
/
A-app-faq.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
\backmatter
# (APPENDIX) Appendix {-}
\newpage
# Frequently Asked Questions {#faq}
The [ggtree mailing-list](https://groups.google.com/forum/?#!forum/bioc-ggtree)^[<https://groups.google.com/forum/?#!forum/bioc-ggtree>] is a great place to get help, once you have created a reproducible example that illustrates your problem.
## Installation {#installation}
The `r Biocpkg("ggtree")` is released within the Bioconductor project; you need to use `r CRANpkg("BiocManager")` to install it.
```r
## you need to install BiocManager before using it
## install.packages("BiocManager")
library(BiocManager)
install("ggtree")
```
Bioconductor release is adhered to a specific R version. Please make sure you are using the latest version of R if you want to install the latest release of Bioconductor packages, including `r Biocpkg("ggtree")`. Beware that bugs will only be fixed in the current release and develop branches. If you find a bug, please follow the guide^[<https://guangchuangyu.github.io/2016/07/how-to-bug-author/>] to report it.
To make it easy to install and load multiple core packages in a single step, we created a meta-package, `r pkg_treedataverse`. Users can install the package via the following command:
```r
BiocManager::install("YuLab-SMU/treedataverse")
```
Once it is installed, loading the package will also load the core `r pkg_treedataverse` packages, including `r CRANpkg("tidytree")`, `r Biocpkg("treeio")`, `r Biocpkg("ggtree")`, and `r Biocpkg("ggtreeExtra")`.
## Basic R Related {#faq-r}
### Use your local file {#faq-local-file}
If you are new to `R` and want to use `r Biocpkg("ggtree")` for tree visualization, please do
learn some basic `R` and `r CRANpkg("ggplot2")`.
A very common issue is that users copy and paste commands without looking at
the function's behavior. The `system.file()` function was used in some of our examples to find files packed in the packages.
```
system.file package:base R Documentation
Find Names of R System Files
Description:
Finds the full file names of files in packages etc.
Usage:
system.file(..., package = "base", lib.loc = NULL,
mustWork = FALSE)
```
For users who want to use their files, please just use relative or absolute file path (*e.g.*, `file = "your/folder/filename"`).
## Aesthetic mapping {#faq-aes-mapping}
### Inherit aesthetic mapping {#faq-inherit-aes}
```r
ggtree(rtree(30)) + geom_point()
```
For example, we can add symbolic points to nodes with `geom_point()` directly.
The magic here is we don't need to map the `x` and `y` position of the points by providing `aes(x, y)` to `geom_point()` since it was already mapped by the `ggtree()` function and it serves as a global mapping for all layers.
But what if we provide a dataset in a layer and the dataset doesn't contain columns of `x` and/or `y`,
the layer function also tries to map `x` and `y` and also others if you map them in the `ggtree()` function.
As these variables are not available in your dataset, you will get the following error:
```
Error in eval(expr, envir, enclos) : object 'x' not found
```
This can be fixed by using the parameter `inherit.aes=FALSE` which will disable inheriting mapping from the `ggtree()` function.
### Never use `$` in aesthetic mapping {#faq-dollar-aes}
Never do this^[<https://groups.google.com/d/msg/bioc-ggtree/hViM6vRZF94/MsZT8qRgBwAJ>
and <https://github.com/GuangchuangYu/ggtree/issues/106>] and please refer to the explanation in the [ggplot2 book 2ed](https://github.com/hadley/ggplot2-book/blob/master/layers.Rmd#L185) [@wickham_ggplot2_2016]:
>Never refer to a variable with `$` (e.g., `diamonds$carat`) in `aes()`. This breaks containment so that the plot no longer contains everything it needs and causes problems if ggplot2 changes the order of the rows, as it does when facetting.
## Text and Label {#faq-text}
### Tip label truncated {#faq-label-truncated}
The reason for this issue is that `r CRANpkg("ggplot2")` can't auto-adjust `xlim` based on added text^[<https://twitter.com/hadleywickham/status/600280284869697538>].
```r
library(ggtree)
## example tree from https://support.bioconductor.org/p/72398/
tree <- read.tree(text= paste("(Organism1.006G249400.1:0.03977,",
"(Organism2.022118m:0.01337,(Organism3.J34265.1:0.00284,",
"Organism4.G02633.1:0.00468)0.51:0.0104):0.02469);"))
p <- ggtree(tree) + geom_tiplab()
```
In this example, the tip labels displayed in Figure \@ref(fig:truncatedTip)A are truncated. This is because the units are in two different spaces (data and pixel). Users can use `xlim` to allocate more spaces for tip labels (Figure \@ref(fig:truncatedTip)B).
```r
p + xlim(0, 0.08)
```
Another solution is to set `clip = "off"` to allow drawing outside of the plot panel. We may also need to set `plot.margin` to allocate more spaces for margin (Figure \@ref(fig:truncatedTip)C).
```r
p + coord_cartesian(clip = 'off') +
theme_tree2(plot.margin=margin(6, 120, 6, 6))
```
(ref:truncatedTipscap) Allocating more spaces for truncated tip labels.
(ref:truncatedTipcap) **Allocating more spaces for truncated tip labels.** Long tip labels may be truncated (A). One solution is to allocate more spaces for plot panel (B), and another solution is to allow plotting labels outside the plot panel (C).
```{r truncatedTip, fig.width=12, fig.height=4, echo=FALSE, fig.cap="(ref:truncatedTipcap)", fig.scap="(ref:truncatedTipscap)", out.width='100%'}
library(ggplot2)
library(ggtree)
## example tree from https://support.bioconductor.org/p/72398/
tree<-read.tree(text="(Organism1.006G249400.1:0.03977,(Organism2.022118m:0.01337,(Organism3.J34265.1:0.00284,Organism4.G02633.1:0.00468)0.51:0.0104):0.02469);")
p <- ggtree(tree) + geom_tiplab()
p2 <- ggtree(tree) + geom_tiplab() + xlim(0, 0.1)
p3 <- p + coord_cartesian(clip = 'off') +
theme_tree2(plot.margin=margin(6, 140, 6, 6))
plot_list(p, p2, p3, ncol=3, tag_levels="A")
```
The third solution is to use `hexpand()` as demonstrated in [session 12.4](#ggexpand).
For rectangular/dendrogram layout trees, users can display tip labels as *y*-axis labels. In this case, no matter how long the labels are, they will not be truncated (see Figure \@ref(fig:tiplab)C).
### Modify (tip) labels {#faq-modify-label}
If you want to modify tip labels of the tree, you can use `treeio::rename_taxa()` to rename a `phylo` or `treedata` object.
```{r renameTaxa}
tree <- read.tree(text = "((A, B), (C, D));")
d <- data.frame(label = LETTERS[1:4],
label2 = c("sunflower", "tree", "snail", "mushroom"))
## rename_taxa use 1st column as key and 2nd column as value by default
## rename_taxa(tree, d)
rename_taxa(tree, d, label, label2) %>% write.tree
```
If the input tree object is a `treedata` instance, you can use `write.beast()` to export the tree with associated data to a BEAST compatible NEXUS file (see [Chapter 3](#chapter3)).
Renaming phylogeny tip labels seems not to be a good idea, since it may introduce problems when mapping the original sequence alignment to the tree. Personally, I recommend storing the new labels as a tip annotation in `treedata` object.
```{r warnings = F}
tree2 <- full_join(tree, d, by = "label")
tree2
```
If you just want to show different or additional information when plotting the tree, you don't need to modify tip labels. This could be easily done via the `%<+%` operator to attach the modified version of the labels and then use the `geom_tiplab()` layer to display
the modified version (Figure \@ref(fig:renameTip)).
(ref:renameTipscap) Alternative tip labels.
(ref:renameTipcap) **Alternative tip labels.** Original tip labels (A) and a modified version (B).
```{r renameTip, fig.width=8, fig.height=3, fig.cap="(ref:renameTipcap)", fig.scap="(ref:renameTipscap)", out.width='100%'}
p <- ggtree(tree) + xlim(NA, 3)
p1 <- p + geom_tiplab()
## the following command will produce an identical figure of p2
## ggtree(tree2) + geom_tiplab(aes(label = label2))
p2 <- p %<+% d + geom_tiplab(aes(label=label2))
plot_list(p1, p2, ncol=2, tag_levels = "A")
```
### Formatting (tip) labels {#faq-formatting-label}
If you want to format labels, you need to set `parse=TRUE` in the `geom_text()`/`geom_tiplab()`/`geom_nodelab()` and the `label` should be a string that can be parsed into expression and displayed as described in `?plotmath`. Users can use the `r CRANpkg("latex2exp")` package to convert LaTeX math formulas to R's plotmath expressions, or use the `r CRANpkg("ggtext")` package to render Markdown or HTML.
For example, the tip labels contain several parts (*e.g.*, genus, species, and geo), we can differentiate these pieces of information with different formats (Figure \@ref(fig:formatTip)A).
```{r formatTip-A, eval=F}
tree <- read.tree(text = "((a,(b,c)),d);")
genus <- c("Gorilla", "Pan", "Homo", "Pongo")
species <- c("gorilla", "spp.", "sapiens", "pygmaeus")
geo <- c("Africa", "Africa", "World", "Asia")
d <- data.frame(label = tree$tip.label, genus = genus,
species = species, geo = geo)
library(glue)
d2 <- dplyr::mutate(d,
lab = glue("italic({genus})~bolditalic({species})~({geo})"),
color = c("#E495A5", "#ABB065", "#39BEB1", "#ACA4E2"),
name = glue("<i style='color:{color}'>{genus} **{species}**</i> ({geo})")
)
p1 <- ggtree(tree) %<+% d2 + xlim(NA, 6) +
geom_tiplab(aes(label=lab), parse=T)
```
Using Markdown or HTML to format text may be easier, and this is supported via the `r CRANpkg("ggtext")` package (Figure \@ref(fig:formatTip)B).
```{r formatTip-B, eval=F}
library(ggtext)
p2 <- ggtree(tree) %<+% d2 +
geom_richtext(data=td_filter(isTip),
aes(label=name), label.color=NA) +
hexpand(.3)
plot_list(p1, p2, ncol=2, tag_levels = 'A')
```
(ref:formatTipscap) Formatting labels.
(ref:formatTipcap) **Formatting labels.** Formatting specific tip labels using `plotmath` expression (A), and Markdown/HTML (B).
```{r formatTip, fig.width=9.2, fig.height=4.2, echo = F, fig.cap="(ref:formatTipcap)", fig.scap="(ref:formatTipscap)", ref.label = c('formatTip-A', 'formatTip-B'), echo=FALSE, out.width='100%'}
```
### Avoid overlapping text labels {#faq-ggrepel}
Users can use the `r CRANpkg("ggrepel")` package to repel overlapping text labels (Figure \@ref(fig:repelTip)).
(ref:repelTipscap) Repel labels.
(ref:repelTipcap) **Repel labels.** Repel labels to avoid overlapping.
```{r repelTip, fig.width=12, fig.height=8, fig.cap="(ref:repelTipcap)", fig.scap="(ref:repelTipscap)", out.width='100%'}
library(ggrepel)
library(ggtree)
raxml_file <- system.file("extdata/RAxML",
"RAxML_bipartitionsBranchLabels.H3", package="treeio")
raxml <- read.raxml(raxml_file)
ggtree(raxml) + geom_label_repel(aes(label=bootstrap, fill=bootstrap)) +
theme(legend.position = c(.1, .8)) + scale_fill_viridis_c()
```
### Bootstrap values from Newick format {#faq-bootstrap}
It is quite common to store *bootstrap* value as node label in the Newick format as in Figure \@ref(fig:nwkbs). Visualizing node label is easy using `geom_text2(aes(subset = !isTip, label=label))`.
If you want to only display a subset of *bootstrap* (*e.g.*, bootstrap > 80), you can't simply use `geom_text2(subset= (label > 80), label=label)` (or `geom_label2`) since `label` is a character vector, which contains node label (bootstrap value) and tip label (taxa name). `geom_text2(subset=(as.numeric(label) > 80), label=label)` won't work either, since `NAs` were introduced by coercion. We need to convert `NAs` to logical `FALSE`. This can be done by the following code:
(ref:nwkbsscap) Bootstrap value stored in node label.
(ref:nwkbscap) **Bootstrap value stored in node label.**
```{r nwkbs, fig.width=12, fig.height=8, fig.cap="(ref:nwkbscap)", fig.scap="(ref:nwkbsscap)", out.width='100%'}
nwk <- system.file("extdata/RAxML","RAxML_bipartitions.H3", package='treeio')
tr <- read.tree(nwk)
ggtree(tr) + geom_label2(aes(label=label,
subset = !is.na(as.numeric(label)) & as.numeric(label) > 80))
```
As this is a very common issue, we implemented a `read.newick()` function in the `r Biocpkg("treeio")` package to allow parsing internal node labels as supported values. As a result, it can be easier to display bootstrap values using the following code:
```r
tr <- read.newick(nwk, node.label='support')
ggtree(tr) + geom_nodelab(geom='label', aes(label=support, subset=support > 80))
```
<!--
Another solution is converting the bootstrap value outside `ggtree`.
q <- ggtree(tr)
d <- q$data
d <- d[!d$isTip,]
d$label <- as.numeric(d$label)
d <- d[d$label > 80,]
q + geom_text(data=d, aes(label=label))
-->
## Branch Setting
### Plot the same tree as in `plot.phylo()`
By default, `ggtree()` ladderizes the input tree so that the tree will appear less cluttered. This is the reason why the tree visualized by `ggtree()` is different from the one using `plot.phylo()` which displays a non-ladderized tree. To disable the ladderize effect, users can pass the parameter `ladderize = FALSE` to the `ggtree()` function as demonstrated in Figure \@ref(fig:ggtreeladderize).
```{r eval=FALSE}
library(ape)
library(ggtree)
set.seed(42)
x <- rtree(5)
plot(x)
ggtree(x, ladderize = FALSE) + geom_tiplab()
ggtree(x) + geom_tiplab()
```
(ref:ggtreeladderizescap) Ladderized and nonladderized tree.
(ref:ggtreeladderizecap) **Ladderized and non-ladderized tree.** `plot.phylo()` displays non-ladderized tree (A), use `ladderize = FALSE` to display non-ladderized tree in `ggtree()` (B), `ggtree()` displays ladderized tree by default (C).
```{r echo=F}
library(ape)
library(ggtree)
library(ggplotify)
set.seed(2020)
x <- rtree(5)
#p1 <- as.ggplot(~plot(x))
#p2 <- ggtree(x, ladderize = FALSE) + geom_tiplab()
#p3 <- ggtree(x) + geom_tiplab()
## don't know why throw error when combine them in bookdown
## it is OK in interactive R terminal
# plot_list(p1, p2, p3, ncol=3, tag_levels = 'A')
```
```{r ggtreeladderize, fig.cap="(ref:ggtreeladderizecap)", fig.scap="(ref:ggtreeladderizescap)", fig.width=8, fig.height=4, echo=FALSE, out.width="100%"}
pg <- readRDS("cache-objs/ladderize-example.rds")
print(pg)
```
### Specifying the order of the tips
The `rotateConstr()` function provided in the `r CRANpkg("ape")` package rotates internal branches based on the specified order of the tips, and the order should be followed when plotting the tree (from bottom to top). As `ggtree()` by default ladderizes the input tree, users need to disable by passing `ladderize = FALSE`. Then the order of the tree will be displayed as expected (Figure \@ref(fig:rotateConstr)). Users can also extract tip order displayed by `ggtree()` using the `get_taxa_name()` function as demonstrated in [session 12.6](#tiporder).
(ref:rotateConstrscap) Specifying tree order.
(ref:rotateConstrcap) **Specifying tree order.** The order of the input tree will be maintained in `ggtree()` when `ladderize = FALSE`.
```{r rotateConstr, fig.cap="(ref:rotateConstrcap)", fig.scap="(ref:rotateConstrscap)", fig.width=6, fig.height=4, out.width="100%"}
y <- ape::rotateConstr(x, c('t4', 't2', 't5', 't1', 't3'))
ggtree(y, ladderize = FALSE) + geom_tiplab()
```
### Shrink outlier long branch
When outgroups are on a very long branch length (Figure \@ref(fig:outgroupEdge)A), we would like to keep the outgroups in the tree but ignore their branch lengths (Figure \@ref(fig:outgroupEdge)B)^[Example from: <https://groups.google.com/d/msg/bioc-ggtree/T2ySvqv351g/mHsyljvBCwAJ>]. This can be easily done by modifying the coordinates of the outgroups (Figure \@ref(fig:outgroupEdge)B). Another approach is to truncate the plot using the `r CRANpkg("ggbreak")` package (Figure \@ref(fig:outgroupEdge)C) [@ggbreak].
(ref:outgroupEdgescap) Shrink outlier long branch.
(ref:outgroupEdgecap) **Shrink outlier long branch.** Original tree (A); reduced outgroup branch length (B); truncated tree plot (C).
```{r outgroupEdge, fig.cap="(ref:outgroupEdgecap)", fig.scap="(ref:outgroupEdgescap)", fig.width=9, fig.height=5, out.width="100%", fig.keep="last"}
library(TDbook)
library(ggtree)
x <- tree_long_branch_example
m <- MRCA(x, 75, 76)
y <- groupClade(x, m)
## A
p <- p1 <- ggtree(y, aes(linetype = group)) +
geom_tiplab(size = 2) +
theme(legend.position = 'none')
## B
p$data[p$data$node %in% c(75, 76), "x"] <- mean(p$data$x)
## C
library(ggbreak)
p2 <- p1 + scale_x_break(c(0.03, 0.09)) + hexpand(.05)
## align plot
plot_list(p1, p, p2, ncol=3, tag_levels="A")
```
### Attach a new tip to a tree {#bind-tip}
Sometimes there are known branches that are not in the tree, but we would like to have them on the tree. Another common scenario is when we have a new sequence species and would like to update the reference tree with this species by inferring its evolutionary position.
Users can use `phytools::bind.tip()` [@revell_phytools_2012] to attach a new tip to a tree. With `r CRANpkg("tidytree")`, it is easy to add an annotation to differentiate newly introduced and original branches and to reflect the uncertainty of the added branch splits off, as demonstrated in Figure \@ref(fig:bindTip).
(ref:bindTipscap) Attaching a new tip to a tree.
(ref:bindTipcap) **Attaching a new tip to a tree.** Different line types were employed to distinguish the newly introduced tip and an error bar was added to indicate the uncertainty of the added branch position.
```{r bindTip, fig.cap="(ref:bindTipcap)", fig.scap="(ref:bindTipscap)", fig.width=6, fig.height=5, out.width="100%"}
library(phytools)
library(tidytree)
library(ggplot2)
library(ggtree)
set.seed(2019-11-18)
tr <- rtree(5)
tr2 <- bind.tip(tr, 'U', edge.length = 0.1, where = 7, position=0.15)
d <- as_tibble(tr2)
d$type <- "original"
d$type[d$label == 'U'] <- 'newly introduced'
d$sd <- NA
d$sd[parent(d, 'U')$node] <- 0.05
tr3 <- as.treedata(d)
ggtree(tr3, aes(linetype=type)) + geom_tiplab() +
geom_errorbarh(aes(xmin=x-sd, xmax=x+sd, y = y - 0.3),
linetype='dashed', height=0.1) +
scale_linetype_manual(values = c("newly introduced" = "dashed",
"original" = "solid")) +
theme(legend.position=c(.8, .2))
```
### Change colors or line types of arbitrarily selected branches
If you want to color or change line types of specific branches, you only need to prepare a data frame with variables of branch setting (e.g., selected and unselected). Applying the Method 1 described in [@yu_two_2018] to map the data onto the tree will make it easy to set colors and line types (Figure \@ref(fig:btype)).
(ref:btypescap) Change colors and line types of specific branches.
(ref:btypecap) **Change colors and line types of specific branches.**
```{r btype, fig.cap="(ref:btypecap)", fig.scap="(ref:btypescap)", fig.width=7, fig.height=5, out.width="100%"}
set.seed(123)
x <- rtree(10)
## binary choices of colors
d <- data.frame(node=1:Nnode2(x), colour = 'black')
d[c(2,3,14,15), 2] <- "red"
## multiple choices of line types
d2 <- data.frame(node=1:Nnode2(x), lty = 1)
d2[c(2,5,13, 14), 2] <- c(2, 3, 2,4)
p <- ggtree(x) + geom_label(aes(label=node))
p %<+% d %<+% d2 + aes(colour=I(colour), linetype=I(lty))
```
Users can use the `r CRANpkg("gginnards")` package to manipulate plot elements for more complicated scenarios.
### Add an arbitrary point to a branch {#arbitrary-point}
If you want to add an arbitrary point to a branch^[<https://twitter.com/melanoidin/status/1262703932993871874>], you can use `geom_nodepoint()`, `geom_tippoint()`, or `geom_point2()` (works for both external and internal nodes) to filter selected node (the endpoint of the branch) via the `subset` aesthetic mapping and specify horizontal position by `x = x - offset` aesthetic mapping, where the offset can be an absolute value (Figure \@ref(fig:pointOnBranch)A) or in proportion to the branch length (Figure \@ref(fig:pointOnBranch)B).
(ref:pointOnBranchscap) Add an arbitrary point on a branch.
(ref:pointOnBranchcap) **Add an arbitrary point on a branch.** The position of the symbolic point can be adjusted by an absolute value (A) or in proportion to the branch length (B).
```{r pointOnBranch, fig.cap="(ref:pointOnBranchcap)", fig.scap="(ref:pointOnBranchscap)", fig.width=8, fig.height=4.5, out.width="100%"}
set.seed(2020-05-20)
x <- rtree(10)
p <- ggtree(x)
p1 <- p + geom_nodepoint(aes(subset = node == 13, x = x - .1),
size = 5, colour = 'firebrick', shape = 21)
p2 <- p + geom_nodepoint(aes(subset = node == 13, x = x - branch.length * 0.2),
size = 3, colour = 'firebrick') +
geom_nodepoint(aes(subset = node == 13, x = x - branch.length * 0.8),
size = 5, colour = 'steelblue')
plot_list(p1, p2, ncol=2, tag_levels="A")
```
## Different *X*-axis Labels for Different Facet Panels
This is not supported by `r CRANpkg("ggplot2")` in general. However, we can just draw text labels for each panel and put the labels beyond the plot panels as demonstrated in Figure \@ref(fig:xlabFacets).
(ref:xlabFacetsscap) *X*-axis titles for different facet panels.
(ref:xlabFacetscap) ***X*-axis titles for different facet panels.**
```{r xlabFacets, fig.width=7, fig.height=5, fig.cap="(ref:xlabFacetscap)", fig.scap="(ref:xlabFacetsscap)", out.width="100%"}
library(ggtree)
library(ggplot2)
set.seed(2019-05-02)
x <- rtree(30)
p <- ggtree(x) + geom_tiplab()
d <- data.frame(label = x$tip.label,
value = rnorm(30))
p2 <- p + geom_facet(panel = "Dot", data = d,
geom = geom_point, mapping = aes(x = value))
p2 <- p2 + theme_bw() +
xlim_tree(5) + xlim_expand(c(-5, 5), 'Dot')
# .panel is the internal variable used in `geom_facet` for faceting.
d <- data.frame(.panel = c('Tree', 'Dot'),
lab = c("Distance", "Dot Units"),
x=c(2.5,0), y=-2)
p2 + scale_y_continuous(limits=c(0, 31),
expand=c(0,0),
oob=function(x, ...) x) +
geom_text(aes(label=lab), data=d) +
coord_cartesian(clip='off') +
theme(plot.margin=margin(6, 6, 40, 6))
```
## Plot Something behind the Phylogeny {#faq-under-the-tree}
The `ggtree()` function plots the tree structure, and normally we add layers on top of the tree.
```{r tree_behind_box}
set.seed(1982)
x <- rtree(5)
p <- ggtree(x) + geom_hilight(node=7, alpha=1)
```
If we want the layers behind the tree layer, we can reverse the order of all the layers.
```r
p$layers <- rev(p$layers)
```
Another solution is to use `ggplot()` instead of `ggtree()` and `+ geom_tree()` to add the layer of tree structure at the correct position of the layer stack (Figure \@ref(fig:treeLayerOrder)).
```r
ggplot(x) + geom_hilight(node=7, alpha=1) + geom_tree() + theme_tree()
```
(ref:treeLayerOrderscap) Add layers behind the tree structure.
(ref:treeLayerOrdercap) **Add layers behind the tree structure.** A layer on top of the tree structure (A). Reverse layer order of A (B). Add layer behind the tree layer (C).
```{r treeLayerOrder, echo=F, fig.width=6, fig.height=3, fig.cap="(ref:treeLayerOrdercap)", fig.scap="(ref:treeLayerOrderscap)", out.width="100%"}
g <- p
p$layers <- rev(p$layers)
cowplot::plot_grid(g, p,
ggplot(x) + geom_hilight(node=7, alpha=1) + geom_tree() + theme_tree(),
ncol = 3, labels = LETTERS[1:3])
```
## Enlarge Center Space in Circular/Fan Layout Tree {#faq-enlarge-center-space}
This question for enlarging center space in circular/fan layout tree was asked several times^[<https://groups.google.com/d/msg/bioc-ggtree/gruC4FztU8I/mwavqWCXAQAJ>, <https://groups.google.com/d/msg/bioc-ggtree/UoGQekWHIvw/ZswUUZKSGwAJ> and <https://github.com/GuangchuangYu/ggtree/issues/95>], and a published example can be found in [@barton_broad_2016]. Increasing the percentage of center white space in a circular tree is useful to avoid overlapping tip labels and to increase the readability of the tree by moving all nodes and branches further out. This can be done simply by using `xlim()` or `hexpand()` to allocate more space (Figure \@ref(fig:circular-space)A), just like in Figure \@ref(fig:layout2)G, or assigning a long root branch that is similar to the "Root Length" parameter in `r pkg_figtree` (Figure \@ref(fig:circular-space)B).
(ref:innerspacescap) Enlarge center space in circular tree.
(ref:innerspacecap) **Enlarge center space in circular tree.** Allocate more space by `xlim` (A) or long root branch (B).
```{r circular-space, fig.width=8, fig.height=4, fig.cap="(ref:innerspacecap)", fig.scap="(ref:innerspacescap)", out.width="100%"}
set.seed(1982)
tree <- rtree(30)
plot_list(
ggtree(tree, layout='circular') + xlim(-10, NA),
ggtree(tree, layout='circular') + geom_rootedge(5),
tag_levels = "A", ncol=2
)
```
## Use the Most Distant Tip from the Root as the Origin of the Timescale
The `revts()` will reverse the *x*-axis by setting the most recent tip to 0. We can use `scale_x_continuous(labels=abs)` to label *x*-axis using absolute values (Figure \@ref(fig:distantTip)).
(ref:distantTipscap) Origin of the time scale.
(ref:distantTipcap) **Origin of the time scale.** Forward: from the root to the tips (A). Backward: from the most distant tip to the root (B).
```{r distantTip, fig.cap="(ref:distantTipcap)", fig.scap="(ref:distantTipscap)", fig.width=6, fig.height=3, out.width="100%"}
tr <- rtree(10)
p <- ggtree(tr) + theme_tree2()
p2 <- revts(p) + scale_x_continuous(labels=abs)
plot_list(p, p2, ncol=2, tag_levels="A")
```
## Remove Blank Margins for Circular Layout Tree {#circular-blank}
For plots in polar coordinates, such as a circular layout tree, it is very common that extra spaces will be generated.
If you are using `Rmarkdown`, you can set the following options for `r CRANpkg("knitr")` to remove extra white space automatically.
```r
library(knitr)
knit_hooks$set(crop = hook_pdfcrop)
opts_chunk$set(crop = TRUE)
```
Otherwise, we can use command-line tools to remove extra white space:
```shell
## for pdf
pdfcrop x.pdf
## for png
convert -trim x.png x-crop.png
```
If you want to do it in R, you can use the `r CRANpkg("magick")` package:
```r
library(magick)
x <- image_read("x.png")
## x <- image_read_pdf("x.pdf") # for PDF
image_trim(x)
```
Here is an example (Figure \@ref(fig:trimSpace)):
(ref:trimSpacescap) Trim extra white space for polar coordinates.
(ref:trimSpacecap) **Trim extra white space for polar coordinates.** Original plot (A). Trimmed version (B).
```{r trimSpace, fig.width=8.8, fig.height=4.5, fig.cap="(ref:trimSpacecap)", fig.scap="(ref:trimSpacescap)", out.width="100%"}
library(ggplot2)
library(ggtree)
library(patchwork)
library(magick)
set.seed(2021)
tr <- rtree(30)
p <- ggtree(tr, size=1, colour="purple", layout='circular')
f <- tempfile(fileext=".png")
ggsave(filename = f, plot = p, width=7, height=7)
x <- image_read(f, density=300)
y <- image_trim(x)
panel_border <- theme(panel.border=element_rect(colour='black',
fill=NA, size=2))
xx <- image_ggplot(x) + panel_border
yy <- image_ggplot(y) + panel_border
plot_list(xx, yy, tag_levels = "A", ncol=2)
```
## Edit Tree Graphic Details {#export-edit}
It can be hard to modify plot details for ordinary users using `r CRANpkg("ggplot2")`/`r Biocpkg("ggtree")`. We recommend using the `r CRANpkg("eoffice")` package to export `r Biocpkg("ggtree")` output to a Microsoft Office Document and edit the tree graphic in PowerPoint.