I am making a phylogenetic tree with forest, using this question and answer as a guide.
I would like to have a vertical axis for time, as shown in the image below but I have two related problems that I do not know how to address.
I would like to have the axis appear to the left of the tree, offset by a specific amount, say 1 cm to the left of the left-most branch (or leaf node label; e.g., gray fox in this example). Right, now, I have to find the distance by trial and error. As the size of tree changes (adding or removing nodes), the axis position should adjust accordingly.
I would like the length of the axis to automatically fit the height of the tree. Right now, I manually count the number of levels and multiply by the value of
l set
(1 cm in this case).
Can both of these be determined programmatically?
\documentclass{article}
\usepackage{forest}
\usetikzlibrary{positioning, backgrounds}
\tikzset{
timeline/.style={align=right, text width=2cm},
no edge from this parent/.style={
every child/.append style={
edge from parent/.style={draw=none}}},
}
\forestset{
every leaf node/.style={
if n children=0{\raggedright #1}{}
},
every tree node/.style={
if n children=0{}{#1}
},
mytree/.style={
for tree={
edge path={
\noexpand\path [draw, ultra thick, \forestoption{edge}] (!u.parent anchor) -| (.child anchor)\forestoption{edge label};
},
every tree node={draw=none,inner sep=0, outer sep=0, minimum size=0},
every leaf node/.style={align=right},
grow'=north,
parent anchor=north,
child anchor=south,
anchor=base,
l sep=1cm,
s sep=3mm,
draw=none,
if n children=0{tier=word, align=center, base=bottom}{}
}
}
}
\begin{document}
\begin{forest} mytree
[, name=lvl0
[,name=lvl1
[,name=lvl2
[gray fox]
[island fox]
]
[
[,name=lvl3
[black\\bear]
[giant\\panda]
]
[
[northern\\elephant\\seal]
[walrus]
]
]
]
]
%
\coordinate (tml) at (-6.5,0);
\begin{scope}[on background layer]
\draw (-5.3,0) -- (-5.3,4) node [above] {\textsc{mya}};
\foreach \x/\age/\len in {1/10/2, 2/7.4/4, 3/4/4}
{
\node[timeline] (age\x) at (lvl\x -| tml) {\age};
\draw[gray, thick, dotted] (age\x) -- (lvl\x);
}
\end{scope}
\end{forest}
\end{document}