树中的形状节点

树中的形状节点

我想创建这棵树,每个节点都有自己的形状。例如每个节点是圆形,叶子是正方形。 在此处输入图片描述

该代码完美运行,但我想在代码中使用树。

\begin{tikzpicture}
    \matrix [column sep=1cm, row sep=1cm] {
        & & \node (in) [draw, shape=circle] {Income}; \\
        \node (lo) [draw, shape=rectangle, minimum size=1cm]    {Loan}; & &
        \node (ms) [draw, shape=circle] {MS}; & & &
        \node (cr) [draw, shape=circle] {CR}; \\
        & \node (lo2) [draw, shape=rectangle, minimum size=1cm] {Loan}; & &
        \node (noLoan) [draw, shape=rectangle, minimum size=1cm] {No loan}; &
        \node (lo3) [draw, shape=rectangle, minimum size=1cm] {Loan}; & &
        \node (noLoan2) [draw, shape=rectangle, minimum size=1cm] {No loan};\\
    };
    \draw[->] (in) -- (lo);
    \draw[->] (in) -- (ms);
    \draw[->] (in) -- (cr);
    \draw[->] (ms) -- (lo2);
    \draw[->] (ms) -- (noLoan);
    \draw[->] (cr) -- (lo3);
    \draw[->] (cr) -- (noLoan2);
\end{tikzpicture}

答案1

使用forest包绘制树。有点复杂,但代码很短:

\documentclass[margin=3mm]{standalone}
\usepackage{forest} % it load tikz too
\usetikzlibrary{arrows.meta}

\begin{document}
    \begin{forest}
for tree =  {
% nodes styles
        draw, 
        minimum size=3em,
        inner sep=2pt,
  where level = 2{}{circle, draw},
        align = center,
       anchor = north,
       %child anchor=north,
% tree style
         edge = {-Straight Barb, semithick},
        s sep = 12 mm,
        l sep = 16 mm,
  where level = 1{s sep=2mm}{},
% edge labels
EL/.style 2 args = {edge label={%
                    node[midway, font=\footnotesize, align=center,
                         inner sep=2pt, anchor=south #1]{#2}},
                    },
            }    
[Income, 
    [loan, rectangle, EL={east}{high}]
    [MS, EL={east}{medium}, 
         before computing xy={s/.average={s}{siblings}}
        [loan, EL={east}{maried}] 
        [no\\ loan, EL={west}{no\\ married}]   
    ]
    [CR, EL={west}{low},
        [loan, EL={east}{good}] 
        [no\\ loan, EL={west}{poor}]   
    ]
]
    \end{forest}
\end{document}

在此处输入图片描述

相关内容