51

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)$)).

2

1 Answer 1

96

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

4
  • 8
    +1 for explanation on '!'. I finally find it here. Thanks! Commented Sep 26, 2013 at 12:51
  • 1
    How do you divide a coordinate by a fixed amount? Do you use the "!" command? Commented Aug 20, 2015 at 1:39
  • 1
    @stars83clouds. Do it w.r.t. origin. For instance, half of coordinate (a) can be written as (a)!0.5!(0,0) Commented Aug 26, 2020 at 13:24
  • After too much work, I have finally found something about the ! in coordinates specification. Is there any official doc about the usage of the exclamation mark? I could not find anything on the manual Commented Jul 7, 2022 at 6:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .