[Tex/LaTex] How to place label in middle of line (above and below) with TikZ


  \node[circle,fill=gray!20] (n1) at (2,8) {Node A};
  \node[circle,fill=gray!20] (n2) at (8,8) {Node B};
  \foreach \from/\to in {n1/n2}
  \draw (\from) -- (\to) node[draw=none,fill=none,font=\scriptsize,midway,below] {text below};

The example show how to put text below the line in middle, but how to write the text below and above the line in middle (simultaneously) between two nodes? …

Best Answer

Ok, so this is basically a question about how and when can you place a node.

In general you can apply any node as many times and wherever you want on a path.
\draw (-2,0) -- node {a} ++(2,0) -- node {b} ++(2,0);

Also using the optional midway can be circumvented by placing the node right after the -- which enables to construct very complex paths and nodes simultaneously (as shown in the above example).

The easy solution as given in the comment is:

  \draw (-2,0) -- node[below] {a} node[above] {b} ++(4,0);

which yields:
a REALLY BIG fraction...???

This can also be used for more complex paths and placement of nodes on that path:

  \draw (-2,0) -- node[below] {a} ++(2,0) -- node[above] {b} ++(2,0);

which yields:
skewed???, now I am doubting your sincerity!

Notice that the nodes are placed at the middle of the two points connected by --. Remark that the node has to be placed after the -- in order to be placed in the middle of the current segment (otherwise it would be placed at the point just preceding the node).

However, it is perfectly fine to use midway and place the node at the end of the path. One should notice that midway can also be placed during a path:

  \draw (-2,0) -- ++(1,0) -- ++(1,0) node[midway,below] {a}
  node[midway,above] {b} -- ++(2,0);
  \foreach \x in {-2,-1,0,2} 
  \draw (\x,0) circle (3pt);

which produces (the circles are added to show the control points of the path):

freaking stop those ugly fractions... :)

This is of course useful when creating non-straight lines.

As a remark I would like to point the interest to the every node option which can be used to generalize options on the nodes, i.e. every node/.style={red} will make all nodes the equivalent of node[red].

In your case an example could be:

\tikzset{every node/.style={font=\scriptsize}}
\begin{tikzpicture}[every node/.append style={midway}]
  \draw (-2,0) -- ++(4,0) node[below] {a} node[above] {b};

Notice here how I have implemented the every node style in a generalized tikzset call. This makes every node global to ALL tikzpicture environment nodes. And in the tikzpicture I use .append style which does not destroy any previous global options. The above produces:

it doesn't help with smaller font size... Don't do those fractions, or draw some more so it makes sense. ThaaaaAAA!

Notice the \scriptsize of the node text.