[Tex/LaTex] tikz relative coordinates

tikz-pgf

Suppose one defines coordinates a and b. One may draw a line connecting these two coordinates (\draw (a) -- (b)). Suppose one desires to draw a line that is shifted upward 1 unit relative to a and b. A first guess is the command \draw (a){}+(0,1) -- (b){}+(0,1). This command, however, connects the point a+(0,1) to the point b, presumably because addition is subsequent to the draw command. How does one obtain the desired result (drawing from a+(0,1) to b+(0,1)?

MWE:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
 \draw[fill] (0,0) circle (2pt) coordinate (a);
 \draw[fill] (5,0) circle (2pt) coordinate (b);
 \draw (a) -- (b);
 \draw (a){}+(0,1) -- (b){}+(0,1);
\end{tikzpicture}
\end{document}

enter image description here

Edit: How does one draw coordinates at a point shifted relative to the arithmetic average of the coordinates of two points (something akin to \node at ($(((s1)+(s2))/2)+(0,1)$)).

Best Answer

You can try this, using the calc library (See Section 13.5 Coordinate Calculations of the pgf manual):

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}

\begin{tikzpicture}
  \coordinate (a) at (2,2);
  \coordinate (b) at (0,-2);
  \node[draw=red] at (a) {a};
  \node[draw=red] at (b) {b};
  \draw[help lines] (-1,-3) grid (3,3);
  \draw ($ (a) + (0,1) $) -- ($ (b) + (0,1) $);
\end{tikzpicture}

\end{document}

enter image description here

To answer the follow-up, you can use partway modifiers (Section 13.5.3 of the manual). For example, the meaning of

(1,2)!.75!(3,4)

is "the coordinate that is three quarters on the way from (1,2) to (3,4)." A little complete example:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}

\begin{tikzpicture}
  \coordinate (a) at (2,2);
  \coordinate (b) at (0,-2);
  \node[draw=red] at (a) {a};
  \node[draw=red] at (b) {b};
  \draw[help lines] (-1,-3) grid (3,3);
  \draw ($ (a) + (0,1) $) -- ($ (b) + (0,1) $);
  \draw[blue,thick] (-1,2) -- ($ (a)!0.5!(b) $) -- (3,2);
  \draw[magenta,thick] (2,-2) -- ($ (a)!0.75!(b) $) -- ($ (a)!0.25!(b) $) -- (3,2);
\end{tikzpicture}

\end{document}

enter image description here