3

When I define a new command to draw an axis I want to use one argument to calculate the step size of the tick numbers. I tried this but it didn't work:

\newcommand{\axistest}[2]{
  \draw[->,color=black] (0,0) -- (#1+0.5,0);
  \foreach \x in {1, ..., #1} {
    \draw[shift={(\x,0)},color=black] (0pt,2pt) -- (0pt,-2pt) node[below] {\footnotesize $#2*\x$};
  }
}

\begin{tikzpicture}
  \axistest{5}{2}
\end{tikzpicture}

I get the following as output:

latex output

But I want the numbers to be 2, 4, 6, etc.

I get the same output when I remove the dollar signs around #2*\x.

1
  • Can you please provide minimal code, we can copy, paste amd run? E.g. besides the preamble there should at least be a call to your newcommand. Thanks
    – MS-SPO
    Jan 20 at 10:55

1 Answer 1

8

You ask TikZ to write text into your nodes, it writes text. If you want to compute a value to be printed into the node, you have to evaluate the label into the foreach definition (for example):

\documentclass[tikz,border=3.14mm]{standalone}
% https://tex.stackexchange.com/q/630831/204164

\begin{document}
    \begin{tikzpicture}
        \draw[->,color=black] (0,0) -- (5+0.5,0);
        \foreach \x [evaluate=\x as \l using int(2*\x)] in {1, ..., 5} {
            \draw[shift={(\x,0)},color=black] (0pt,2pt) -- (0pt,-2pt) node[below] {\footnotesize $\l$};
            }
    \end{tikzpicture}
\end{document}

foreach and computation

Since you didn't provide an MWE, I didn't insert the commands into a newcommand, but I'm sure you could figure it out by yourself.

1
  • 2
    That's the thing I was looking for! Works as expected, thank you! Jan 20 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.