6

I would like to display the evaluation of data on node instead display the values. What I mean is instead \x + 3*\y evaluate to 0 + 3*0 it should display 0, the result of calculation. How to do that?

\documentclass [12pt]{article}
\begin{document}
\begin{tikzpicture}[y=-1cm]{every node/.style={font=\scriptsize}}
\draw [step=.1cm,very thin,black!10] (0,0) grid (6,6);
\draw [step=2cm,thin,black!50] (0,0) grid (6,6);
\draw [very thick,black] (0,0) rectangle (6,6);
\draw [->,very thick] (0,0) --  (6.5,0) node[below] {$X$};
\draw [->,very thick] (0,0) --  (0,6.5) node[right] {$Z$};

    \foreach \x in {0,1,...,2} {
        \foreach \y in {0,1,...,2} {
            \node (node) [label={[yshift=-.6cm, xshift=.3cm]:\x + 3*\y}] at (2*\x,2*\y) {};
        }
    }
\end{tikzpicture}
\end{document}
6

I would evaluate it as part of the loop. For example,

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[y=-1cm]{every node/.style={font=\scriptsize}}
  \draw [step=.1cm,very thin,black!10] (0,0) grid (6,6);
  \draw [step=2cm,thin,black!50] (0,0) grid (6,6);
  \draw [very thick,black] (0,0) rectangle (6,6);
  \draw [->,very thick] (0,0) --  (6.5,0) node[below] {$X$};
  \draw [->,very thick] (0,0) --  (0,6.5) node[right] {$Z$};

  \foreach \x in {0,1,...,2} {
    \foreach \y [evaluate=\y as \z using {int(\x+3*\y)}] in {0,1,...,2} {
      \node (node) [label={[yshift=-.6cm, xshift=.3cm]:\z}] at (2*\x,2*\y) {};
    }
  }
\end{tikzpicture}
\end{document}

results in picture

Alternatively, you could calculate \z within the loop. For example,

\pgfmathsetmacro\z{int(\x+3*\y)}

before typesetting the \node would effectively do the same thing.

EDIT [Response to follow-up]

You could just put the labels inside the nodes and set the anchor as you wish, rather than messing around with shifts. For example,

\node  [anchor=north west] at (2*\x,2*\y) {\z};

produces

anchored labelling nodes

5

You can evaluate expressions with the suitable keys in a for loop. Hence if you change your code to

    \foreach \y[evaluate={\yi=int(\x + 3*\y);}] in {0,1,...,2} {
        \node (node) [label={[yshift=-.6cm, xshift=.3cm]:\yi}] at (2*\x,2*\y) {};

Here int is needed to return integers instead of 1.0, 2.0... etc.

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.