Why do we have to explicitly append the unit for xshift and yshift?

You could use shift={(1,2)} or shift={(1,0)},shift={(0,2)}. Both result in

enter image description here

Code:

\documentclass[tikz,border=12pt]{standalone}
\begin{document}
\begin{tikzpicture}
    \draw[gray!50] (-4,-4) grid (4,4);
    \begin{scope}[>=stealth,<->]
        \draw (-4,0) -- (4,0);
        \draw (0,-4) -- (0,4);
    \end{scope}
    \draw (0,0) rectangle (2,1)[red]
      [shift={(1,2)}] (0,0) rectangle (2,1)
      %[shift={(1,0)},shift={(0,2)}] (0,0) rectangle (2,1)
    ;
\end{tikzpicture}
\end{document}

You could also define new styles:

\documentclass[tikz,border=12pt]{standalone}
\tikzset{
  my xshift/.style={shift={(#1,0)}},
  my xshift/.value required,
  my yshift/.style={shift={(0,#1)}},
  my yshift/.value required
}
\begin{document}
\begin{tikzpicture}
    \draw[gray!50] (-4,-4) grid (4,4);
    \begin{scope}[>=stealth,<->]
        \draw (-4,0) -- (4,0);
        \draw (0,-4) -- (0,4);
    \end{scope}
    \draw[red] (0,0) rectangle (2,1)
      [my xshift=1, my yshift=2] (0,0) rectangle (2,1)
    ;
\end{tikzpicture}
\end{document}

The result is the same as above.


You only have to give the unit if you want it to not be the default. But which unit is default depends on the context. In coordinate specifications, it is one of whatever the standard x / y unit is - 10mm by default. In xshift and yshift it is 1pt.

\documentclass[tikz,border=12pt]{standalone}
\begin{document}
\begin{tikzpicture}
    \draw[gray!50] (-4,-4) grid (4,4);
    \begin{scope}[>=stealth,<->]
        \draw (-4,0) -- (4,0);
        \draw (0,-4) -- (0,4);
    \end{scope}
    \draw (0,0) rectangle (2,1)[red] [xshift=1cm, yshift=2cm] (0,0) rectangle (2,1);
    \draw [thick] (0,0) rectangle (2,1)[blue] [xshift=1, yshift=2] (0,0) rectangle (2,1);
    \draw (0,0) rectangle (2,1)[green] [xshift=1pt, yshift=2pt] (0,0) rectangle (2,1);
\end{tikzpicture}
\end{document}

demo rectangles

Tags:

Tikz Pgf