我将在整个项目中使用相同的基本椭圆/方框图像。我希望在整个项目中保持图像的标准外观,但每次使用图像时都希望更改文本。在此示例中,椭圆包含单词“抑郁”,方框包含“睡眠”和“体重”。但在另一个示例中,我可能会使用“成功”、“GPA”、“GRE”等词。
有没有办法做到这一点(也许使用某种动态变量结构)?
\newcommand{\myModelOneTwo}[1][]{%
\begin{center}
\begin{tikzpicture}
\node(IV)[ellipse, draw, fill=blue!20, minimum width=75pt, minimum height=50pt] at (0,0) {Depression};
\node(IVIndicator1)[rectangle, draw, fill=blue!20, minimum width=50pt, minimum height=25pt] at (-1,-2) {Sleep};
\node(IVIndicator2)[rectangle, draw, fill=blue!20, minimum width=50pt, minimum height=25pt] at (1,-2) {Weight};
\path [->,draw,thick] (IVIndicator1) -- (IV);
\path [->,draw,thick] (IVIndicator2) -- (IV);
\end{tikzpicture}
\end{center}}
答案1
定义一个有 3 个参数的命令。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\newcommand{\myModelOneTwo}[3]{% <<<<<<<<<<<
\begin{center}
\begin{tikzpicture}
\node(IV)[ellipse, draw, fill=blue!20, minimum width=75pt, minimum height=50pt] at (0,0) {#1};
\node(IVIndicator1)[rectangle, draw, fill=blue!20, minimum width=50pt, minimum height=25pt] at (-1,-2) {#2};
\node(IVIndicator2)[rectangle, draw, fill=blue!20, minimum width=50pt, minimum height=25pt] at (1,-2) {#3};
\path [->,draw,thick] (IVIndicator1) -- (IV);
\path [->,draw,thick] (IVIndicator2) -- (IV);
\end{tikzpicture}
\end{center}}
\begin{document}
\myModelOneTwo{Depression}{Sleep}{Weight}
\bigskip
\myModelOneTwo{Success}{GPA}{GRE}
\end{document}
答案2
\newcommand
定义一个新的宏,它可以接受多个参数(最多 9 个),包括一个可选参数。
为了简化代码,tikz
还有一个定义样式的选项,我们可以在代码中重复使用它们。这可以通过tikzset{}
创建图片时或直接创建来完成。我在示例中选择了第一种方法。我还添加了样式,global
只是为了演示您甚至可以在其他样式中使用已经定义的样式。
这个例子
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\tikzset{
general/.style = {
draw,
fill = blue!20,
},
myshapea/.style = {
general,
ellipse,
minimum width=75pt,
minimum height=50pt
},
myshapeb/.style = {
general,
rectangle,
minimum width=50pt,
minimum height=25pt
},
thickarrow/.style = {
->,
draw,
thick,
},
}
\newcommand{\myModelOneTwo}[3][Depression]{
\begingroup
\centering
\begin{tikzpicture}
\node [myshapea] (IV) at ( 0, 0) {#1};
\node [myshapeb] (IVIndicator1) at (-1,-2) {#2};
\node [myshapeb] (IVIndicator2) at ( 1,-2) {#3};
\path [thickarrow] (IVIndicator1) -- (IV);
\path [thickarrow] (IVIndicator2) -- (IV);
\end{tikzpicture}
\par
\endgroup}
\begin{document}
\myModelOneTwo{Sleep}{Weight}
\bigskip
\myModelOneTwo[Success]{GPA}{GRE}
\end{document}