TikZ - 節點樣式取決於節點值

TikZ - 節點樣式取決於節點值

在 tikzpicture 中,我想根據節點的值對節點套用不同的樣式。例如,在整數清單中,我想將節點著色為紅色或藍色。

這只是對更大項目的測試,但無論如何,對此的答案應該會有所幫助。

以下程式碼正在運行:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgffor}
\usepackage{ifthen}

\begin{document}

\begin{tikzpicture}
    \pgfmathdeclarerandomlist{nums}{{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}}
    \foreach \x in {1,...,10}
        {
        \pgfmathrandomitem{\choice}{nums}
        \ifthenelse{\choice<5}
            {
            \node[circle, fill=blue!50] at (\x,0) {\choice};
            }
            {
            \node[circle,fill=red!50] at (\x,0) {\choice};
            }
        }
\end{tikzpicture}

\end{document}

在此輸入影像描述

但是,我想要做的是根據節點的值來建立節點樣式。這樣,我可以新增更多案例,並且只使用 \node 行一次。我嘗試了最簡單的方法來實現這一目標,但它不起作用:

\begin{tikzpicture}
    \pgfmathdeclarerandomlist{nums}{{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}}
    \foreach \x in {1,...,10}
        {
        \pgfmathrandomitem{\choice}{nums}
        \def\clr{\ifthenelse{\choice<5}{blue!50}{red!50}}
        \node[circle, fill=\clr] at (\x,0) {\choice};
        }
\end{tikzpicture}

總之,我想要的是一系列 ifthenelse 到 tikz 風格。這也行不通。似乎 \ifthenelse 不符合每個 TikZ 結構...

如果您知道如何幫助我解決此問題,請提前致謝。

答案1

除其他數學運算符外,Pgf/Tikz 有自己的if-then-else構造。參見部分95.2 數學表達式的語法:運算符 手冊的內容。

您在第二個片段中提出的建議實際上可以透過以下腳本來實現。

\documentclass{article}
\usepackage{tikz}
\usepackage{pgffor}
\usepackage{ifthen}

\tikzset{
    conditionalcolor/.style={circle,fill=#1}
}

\begin{document}

\begin{tikzpicture}
    \pgfmathdeclarerandomlist{nums}{{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}}
    \foreach \x in {1,...,10}{
            \pgfmathrandomitem{\choice}{nums}
            \pgfmathsetmacro{\col}{ifthenelse(\choice<5,"blue!50","red!50")}
            \node[conditionalcolor=\col] at (\x,0) {\choice};
        }
\end{tikzpicture}

\end{document}

編輯這是在整數區間產生隨機數的程式碼。

\documentclass{article}
\usepackage{tikz}

\tikzset{
    conditionalcolor/.style={circle,fill=#1}
}

\begin{document}
\begin{tikzpicture}
    \foreach \x in {1,...,10}{
            \pgfmathtruncatemacro{\choice}{random(0,9)}
            \pgfmathsetmacro{\col}{ifthenelse(\choice<5,"blue!50","red!50")}
            \node[conditionalcolor=\col] at (\x,0) {\choice};
        }
\end{tikzpicture}

\end{document}

相關內容