根据条件在 tikzpicture 中相对定位节点

根据条件在 tikzpicture 中相对定位节点
\begin{tikzpicture}[node distance={20mm}, thick, main/.style = {draw, ellipse}]
    \node[main] (0) {0};
    \node[main, below=10mm of 0] (1) {1};
    \node[main, below=10mm of 1] (2) {2};
    \node[main, right=10mm of 1] (3) {3};
    \node[main,\ifthenelse{1>0}{above}{below}=10mm of 3] (4) {4};
\end{tikzpicture}

我想根据条件将节点 4 放置在节点 3 的上方或下方。我该如何实现?到目前为止,我只收到以下错误消息:

\XC@definec@lor 的参数有一个额外的}。...\ifthenelse{1>0}{above}{below}=10mm of 3]

答案1

受到IfValueTFtcolorbox 的 key 的启发,您可以创建如下内容:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{positioning,shapes}
\usepackage{ifthen}

\tikzset{
  ifthen/.code n args={3}{
    \ifthenelse{#1}{\pgfkeysalso{#2}}{\pgfkeysalso{#3}}
  }
}

\begin{document}

\begin{tikzpicture}[node distance={20mm}, thick, main/.style = {draw, ellipse}]
    \node[main] (0) {0};
    \node[main, below=10mm of 0] (1) {1};
    \node[main, below=10mm of 1] (2) {2};
    \node[main, right=10mm of 1] (3) {3};
    \node[
      main,
      ifthen={1<0}{above=10mm of 3}{below=10mm of 3}
    ] (4) {4};
\end{tikzpicture}

\end{document}

在此处输入图片描述

答案2

这个例子有效。(带包ifthen

\documentclass[12pt,a4paper]{article}

\usepackage{tikz}
\usetikzlibrary{positioning}
\usetikzlibrary{shapes.geometric}
\usepackage{ifthen} 

\begin{document}        
    
    \textbf{\#4 above \#3}\medskip
    \newcommand{\z}{0}      
    
    \begin{tikzpicture}[node distance={20mm}, thick, main/.style = {draw, ellipse}]
        \node[main] (0) {0};
        \node[main, below=10mm of 0] (1) {1};
        \node[main, below=10mm of 1] (2) {2};
        \node[main, right=10mm of 1] (3) {3};
        \ifthenelse{1>\z}{\node[main,above=10mm of 3] (4) {4};}{\node[main,below=10mm of 3] (4) {4};}
    \end{tikzpicture}

    \bigskip        
    
    \textbf{\#4 below \#3}\medskip      
    \renewcommand{\z}{2}

\begin{tikzpicture}[node distance={20mm}, thick, main/.style = {draw, ellipse}]
    \node[main] (0) {0};
    \node[main, below=10mm of 0] (1) {1};
    \node[main, below=10mm of 1] (2) {2};
    \node[main, right=10mm of 1] (3) {3};
    \ifthenelse{1>\z}{\node[main,above=10mm of 3] (4) {4};}{\node[main,below=10mm of 3] (4) {4};}
\end{tikzpicture}
    
\end{document}

A

相关内容