[Tex/LaTex] Tikz: Placing node midway right or left relative to path

positioningtikz-nodetikz-pgf

I'd like to place a node at some position along a path, e.g.

\tikz (a)node[pos=0.5,left]{x}{b};

But instead of shifting it 'left', 'right', 'above' or 'below' in absolute coordinates, I would like to have it left or right of the path relative to the direction of the path. E.g. if the path goes horizontally from the right to the left side of the canvas, 'right' should place it above the line. The node should not be rotated, and it should work not only for straight lines but for curved paths also.

What is the easiest solution for this in Tikz?

Best Answer

This is what the auto option does. By default it places the nodes on the left side of the line, looking along the path. You can move it to the other side by adding the swap option.

enter image description here

\documentclass[border = 2mm]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[
  every node/.style={inner sep=0pt} % to make it clearer which line the nodes belong to
]
\foreach \Ang in {0,45,...,350}
\foreach \Ang in {0,45,...,350}
{
  \draw (0,0) --node[auto] {a} (\Ang:2cm);
  \draw (5,0) to[bend left] node[auto,swap] {a} ++(\Ang:2cm);
}
\end{tikzpicture}
\end{document}
Related Question