我需要在 tikz 森林图中的节点文本中换行。我尝试在节点文本中添加 \ 或 \newline,但没有成功。
以下是示例代码:
\documentclass{article}
\usepackage{tikz}
\usepackage[edges]{forest}
\begin{document}
\begin{figure}[!ht]
\centering
\begin{forest}
forked edges, folder indent=1cm,
where={level()<1}{}{folder, grow'=east},
where={level()>0}{l sep+=1cm}{},
for tree={
fork sep=4mm,
thick, edge=thick,
font=\sffamily,
if n children=0{if n=1{yshift=-5mm}{}, for parent={s sep=0mm}}{draw, minimum height=4ex, minimum width=4cm}
}
[Lorem ipsum dolor sit amet con, calign=edge midpoint, s sep=2cm, font=\bfseries\sffamily
[Lorem ips
[Lorem ipsum
[Lorem ipsum dolor sit.]
[Lorem ipsum dolor s]
]
[Lorem ipsum dolor si
[Lorem ipsum dolor s]
[Lorem ipsum dolo]
]
]
[Lorem ipsum dolor sit am
[Lorem ipsum d]
[Lorem ipsum]
[Lorem ipsum]
]
]
\end{forest}
\caption{A small tree}
\label{fig:smart_card_types}
\end{figure}
\end{document}
答案1
只需在任何地方添加align=center
即可,但如果在根节点或叶节点中添加换行符,则会产生奇怪的结果。对于根节点,我们需要进行调整anchor
以避免“挤压”子节点的路径。对于叶节点,我们需要根据我们在这里想要的内容进行更改和修改。对于这些节点,child anchor
最好也使用它。align=left
\documentclass[border=10pt]{standalone}
\usepackage[edges]{forest}
\begin{document}
\begin{forest}
forked edges,
folder indent=1cm,
anchor=children,
for descendants={l sep'+=1cm,folder,grow'=east},
for tree={
fork sep'=4mm,
thick, edge=thick,
font=\sffamily,
if n children=0{
if n=1{yshift=-5mm}{},
for parent={s sep'=0mm},
align=left,
edge path'={%
(!u.parent anchor) -- ++(\forestoption{fork sep},0pt) |- ([yshift=-.75\baselineskip].child anchor)
},
child anchor=north west,
}{
draw,
minimum height=4ex,
minimum width=4cm,
align=center,
}
},
[Lorem ipsum dolor\\sit amet con, calign=edge midpoint, s sep'=2cm, font=\bfseries\sffamily
[Lorem ips
[Lorem ipsum
[Lorem ipsum\\dolor sit.]
[Lorem ipsum dolor s]
]
[Lorem ipsum\\dolor si
[Lorem\\ipsum\\dolor\\s]
[Lorem ipsum dolo]
]
]
[Lorem ipsum\\dolor sit am
[Lorem ipsum d]
[Lorem ipsum]
[Lorem ipsum]
]
]
\end{forest}
\end{document}
由于过度热衷于换行,结果看起来有些愚蠢:
我还从 OP 原文中删除了一些不必要的代码。
答案2
添加对齐(align
)键,然后您可以使用\\
它将文本分成不同的行。
\documentclass{article}
\usepackage{tikz}
\usepackage[edges]{forest}
\begin{document}
\begin{figure}[!ht]
\centering
\begin{forest}
forked edges, folder indent=1cm,
where={level()<1}{}{folder, grow'=east},
where={level()>0}{l sep+=1cm}{},
for tree={
align=center, %% ADDED
fork sep=4mm,
thick, edge=thick,
font=\sffamily,
if n children=0{if n=1{yshift=-5mm}{}, for parent={s sep=0mm}}{draw, minimum height=4ex, minimum width=4cm}
}
[Lorem ipsum dolor sit amet con, calign=edge midpoint, s sep=2cm, font=\bfseries\sffamily
[Lorem ips
[Lorem ipsum
[Lorem ipsum dolor sit.]
[Lorem ipsum dolor s]
]
[Lorem ipsum dolor si
[Lorem ipsum dolor s]
[Lorem ipsum dolo]
]
]
[Lorem ipsum\\dolor sit am
[Lorem ipsum d]
[Lorem\\ipsum]
[Lorem ipsum]
]
]
\end{forest}
\caption{A small tree}
\label{fig:smart_card_types}
\end{figure}
\end{document}
输出: