我是 LaTeX 的初学者,这是我的第一份文档。
我需要计算森林中的每个节点以及不同颜色的节点,但我不知道聚合函数 .count 如何工作。
这是代码,图片显示了我想要的。
真正的森林有超过 100 个节点,所以我需要自动计数。
\documentclass[tikz,border=5pt,multi]{standalone}
\usepackage{forest,array}
\usepackage[T1]{fontenc}
\begin{document}
\newcolumntype{C}[1]{>{\centering}p{#1}}
\begin{forest}
for tree={
if level=0{align=center}{% allow multi-line text and set alignment
align={@{}C{45mm}@{}},
},
grow'=0,
draw,
edge path={
\noexpand\path [draw, \forestoption{edge}] (!u.parent anchor) -- +(5mm,0) |- (.child anchor)\forestoption{edge label};
},
parent anchor=east,
child anchor=west,
l sep=10mm,
tier/.wrap pgfmath arg={tier #1}{level()},
edge,
rounded corners=2pt
}
[a
[b
[c
[D, draw=green]
]
]
[1]
[2
[3, tikz={\node [draw=red,inner sep=1,fit to=tree,
label=right:\emph{selection}] {};}
[4]
[5, draw=green]
]
]
[6]
[7, tikz={\node [draw=red,inner sep=+1,fit to=tree,
label=right:\emph{selection}] {};}, draw=green]
]
\end{forest}
\end{document}
答案1
以下是一项建议:
\documentclass[tikz,border=5pt,multi]{standalone}
\usepackage{forest,array}
\usepackage[T1]{fontenc}
\begin{document}
% count forest nodes
\newcounter{forestnodes}
\tikzset{
count forest node/.code={\stepcounter{forestnodes}},
reset forest nodes counter/.code={\setcounter{forestnodes}{0}},
}
% count green forest nodes
\newcounter{forestgreennodes}
\tikzset{
count green forest node/.code={\stepcounter{forestgreennodes}},
reset green forest nodes counter/.code={\setcounter{forestgreennodes}{0}},
green node/.style={draw=green, count green forest node},
}
\newcolumntype{C}[1]{>{\centering}p{#1}}
\begin{forest}
for tree={
if level=0{align=center}{% allow multi-line text and set alignment
align={@{}C{45mm}@{}},
},
grow'=0,
draw,
edge path={
\noexpand\path [draw, \forestoption{edge}] (!u.parent anchor) -- +(5mm,0) |- (.child anchor)\forestoption{edge label};
},
parent anchor=east,
child anchor=west,
l sep=10mm,
tier/.wrap pgfmath arg={tier #1}{level()},
edge,
rounded corners=2pt,
/tikz/reset forest nodes counter,
/tikz/reset green forest nodes counter,
node options={count forest node},
}
[a
[b
[c
[D, green node]
]
]
[1]
[2
[3, tikz={\node [draw=red,inner sep=1,fit to=tree,
label=right:\emph{selection}] {};}
[4]
[5, green node]
]
]
[6]
[7, tikz={\node [draw=red,inner sep=+1,fit to=tree,
label=right:\emph{selection}] {};}, green node]
]
\end{forest}
\arabic{forestnodes}
\arabic{forestgreennodes}
\end{document}