具有多个参数的 TikZ 宏

具有多个参数的 TikZ 宏

我正在尝试为自己创建一个简单的(希望如此)宏,以便更高效地使用 TikZ 绘制数字线。我可以手动绘制这样的线条,但由于我需要很多类似的图片,所以宏非常有用。

不过还有一点需要注意:想要宏中的右括号,\tikz{}因为我希望在主体中实际使用它时能够在宏中添加其他路径。

这一切可能吗?

在我的 MWE 中,我手动制作了一条从 0 到 3 的数字线,每个季度都有刻度标记。这有效。旨在创建完全相同内容的宏没有起作用。我在这里遗漏了什么?

谢谢!

\documentclass{article}

\usepackage{tikz}

% THE MACRO THAT DIDN'T WORK
\newcommand{\NL}[4]
{\tikz[xscale=[#1],yscale=[#2]]
 {
 \draw(0,0)--([#3],0);
 \foreach \x in {0,...,[#3]}
  \node[below] at (\x,-0.2) {\x};
 \foreach \x in {0,...,[#3]*[#4]}
  \draw (\x,-0.2)--(\x,0.2);
 }
}

\begin{document}

Number line from 0 to 3 with tick marks at every quarter.

MANUAL WAY
\tikz[xscale=4,yscale=1.2]
{\draw (0,0)--(3,0);
 \foreach \x in {0,...,3}
  \node[below] at (\x,-0.3) {\x};
 \foreach \x in {0,...,12}
  \draw (\x/4,-0.2)--(\x/4,0.2);
}


ATTEMPT TO MAKE EXACTLY THE SAME NUMBER LINE WITH THE MACRO
\NL{4}{1.2}{3}{4}
% xscale of 4, yscale of 1.2, x-axis from 0 to 3, denominator of quarters

\end{document}

答案1

基本元素都在那里。但是,您需要删除参数周围的方括号并#3*#4预先进行计算:

\newcommand{\NL}[4]
{\tikz[xscale=#1,yscale=#2]
 {
 \draw(0,0)--(#3,0);
 \foreach \x in {0,...,#3}
  \node[below] at (\x,-0.2) {\x};
  \pgfmathparse{#3*#4}
 \foreach \x in {0,...,\pgfmathresult}
  \draw (\x/#4,-0.2)--(\x/#4,0.2);
 }%
}

完整代码:

\documentclass{article}
\usepackage{tikz}

\newcommand{\NL}[4]
{\tikz[xscale=#1,yscale=#2]
 {
 \draw(0,0)--(#3,0);
 \foreach \x in {0,...,#3}
  \node[below] at (\x,-0.2) {\x};
  \pgfmathparse{#3*#4}
 \foreach \x in {0,...,\pgfmathresult}
  \draw (\x/#4,-0.2)--(\x/#4,0.2);
 }%
}

\begin{document}

Number line from 0 to 3 with tick marks at every quarter.

MANUAL WAY

\tikz[xscale=4,yscale=1.2]
{\draw (0,0)--(3,0);
 \foreach \x in {0,...,3}
  \node[below] at (\x,-0.3) {\x};
 \foreach \x in {0,...,12}
  \draw (\x/4,-0.2)--(\x/4,0.2);
}


ATTEMPT TO MAKE EXACTLY THE SAME NUMBER LINE WITH THE MACRO

\NL{4}{1.2}{3}{4}

\end{document}

结果:

在此处输入图片描述

如果你有兴趣在 中添加一些额外的东西tikzpicture,那么在定义中使用不匹配的右括号并不是一个明智的做法;我建议你使用类似

\newcommand{\NL}[2]{
 \draw(0,0)--(#1,0);
 \foreach \x in {0,...,#1}
  \node[below] at (\x,-0.2) {\x};
  \pgfmathparse{#1*#2}
  \foreach \x in {0,...,\pgfmathresult}
  \draw (\x/#2,-0.2)--(\x/#2,0.2);
}

进而

\begin{tikzpicture}[xscale=4,yscale=1.2]
\NL{3}{4}
% other tikz stuff
\end{tikzpicture}

相关内容