重复图片中TikZ节点的改变填充

重复图片中TikZ节点的改变填充

用 TikZ 绘制的图表用了几次,我为它定义了一个命令。

在第一张图片中,我想用浅灰色填充来标记节点的一个子集,在第二张图片中标记另一个节点子集。这可行吗,还是我需要为此重复整个命令?

MWE 显示所需节点填充之前的输出。

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usetikzlibrary{positioning,shapes,arrows}

\tikzstyle{main}=[circle, minimum size = 10mm, thick, draw =black!80, fill = white!100, node distance = 12mm]
\tikzstyle{connect}=[-latex, thick]
\tikzstyle{box}=[rectangle, draw=black!100]
\newcommand{\model}{
  \node[main] (alpha) {$\alpha$};
  \node[main] (gamma) [right=of alpha] {$\lambda$};
  \node[main] (Z) [below=of alpha] {$Z$};
  \node[main] (C) [below=of gamma] {$C$};
  \node[main] (W) [right=of C] {$W$};
  \node[main] (R) [below=of W, fill=lightgray] {$R$};
  \node[main] (bias) [above=of W] {$b$};
  \node[main] (sigma) [right=of bias] {$\sigma$};
  \path (alpha) edge [connect] (Z)
    (gamma) edge [connect] (C)
    (Z) edge [connect] (C)
    (C) edge [connect] (R)
    (W) edge [connect] (R)
    (bias) edge [connect, bend left] (R)
    (sigma) edge [connect, bend left] (R)
    (C) edge [connect] (W);
}
\begin{document}
\begin{tikzpicture}
\model
%TODO: fill some nodes here
\end{tikzpicture}

\begin{tikzpicture}
\model
%TODO: fill other nodes here
\end{tikzpicture}
\end{document}

输出

答案1

/.list您可以使用(用于将相同的关键机制重复到逗号分隔的参数列表)和/.try(用于检查是否声明了任何样式)处理程序来提出自己的选项集。这是一个非常基本的设置。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,shapes,arrows}

\tikzset{main/.style={circle, minimum size = 10mm, thick, draw =black!80, fill = white!100, node distance = 12mm},
        connect/.style={-latex, thick},
        box/.style={rectangle, draw=black!100},
        furnish/.style args={#1 with #2}{
            /tikz/my #1/.append style={#2}
            }
        }

\newcommand{\model}[1]{
\tikzset{furnish/.list={#1}}
  \node[main,my alpha/.try] (alpha) {$\alpha$};
  \node[main,my gamma/.try] (gamma) [right=of alpha] {$\lambda$};
  \node[main,my Z/.try] (Z) [below=of alpha] {$Z$};
  \node[main,my C/.try] (C) [below=of gamma] {$C$};
  \node[main,my W/.try] (W) [right=of C] {$W$};
  \node[main,my R/.try] (R) [below=of W] {$R$};
  \node[main,my bias/.try] (bias) [above=of W] {$b$};
  \node[main,my sigma/.try] (sigma) [right=of bias] {$\sigma$};
  \path (alpha) edge [connect] (Z)
    (gamma) edge [connect] (C)
    (Z) edge [connect] (C)
    (C) edge [connect] (R)
    (W) edge [connect] (R)
    (bias) edge [connect, bend left] (R)
    (sigma) edge [connect, bend left] (R)
    (C) edge [connect] (W);
}
\begin{document}

\begin{tikzpicture}
\model{gamma with {rectangle,fill=gray!10},W with {opacity=0.5},R with {fill=lightgray}}
\end{tikzpicture}

\end{document}

在此处输入图片描述

强制链接:)

应该使用 \tikzset 还是 \tikzstyle 来定义 TikZ 样式?

相关内容