I have created a simple node-edge graph in which I would like to have the texts on each edge aligned to the direction of the edge.
\documentclass[class=minimal,border=0pt]{standalone}
\usepackage{pgf}
\usepackage{tikz}
\usetikzlibrary{arrows,automata}
\usepackage[latin1]{inputenc}
\begin{document}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=2.8cm,
semithick]
\tikzstyle{every state}=[fill=red,draw=none,text=white]
\node[state] (D) {$D$};
\node[state] (C) [below right of=D] {$C$};
\node[state] (B) [above right of=D] {$B$};
\node[state] (A) [below right of=B] {$A$};
\path (D) edge node {tdc} (C)
(B) edge node {tbc} (C)
(C) edge node {tca} (A);
\end{tikzpicture}
\end{document}
For example, I would like the text tbc
rotates -90
degrees automatically to be aligned to the direction of the edge connects the node B
to the node C
. Is that possible?
Best Answer
The answer to the question of how to get the text to go along the path is to use the
sloped
key. This rotates the node to match the tangent of the path at the point at which the node would be placed (see Section 16.8 of the PGF Manual).However, as noted in the comments, this doesn't quite work as desired. This is because of the
auto
key. This shifts the node off the path. It does so by placing one of the node anchors at the placement point, the anchor chosen appropriately for the tangent of the path (I haven't looked at the code so I'm guessing as to how it chooses it). The problem comes with the fact that the anchor is chosen first and then the node is rotated. What ought to happen is that the node is rotated and then the anchor is chosen. But actually, this doesn't need any complicated code since the anchor will always be one ofnorth
orsouth
(ifallow upside down
is set then it will always besouth
). So simply settinganchor=south
instead ofauto
will do.Here's a simple example demonstrating the above analysis. The first three nodes are not
sloped
, the second three are. The first of the triples has no (other) options, the second isauto
and the third isanchor=south
. It's clear from the 2nd and 5th that the node has effectively been rotated around its anchor point.Here's your code with this change (plus a couple of minor stylistic changes:
tikz
loadspgf
automatically, and\tikzstyle
is depreciated).(NB the
auto=false
isn't necessary as theanchor=south
overrides theauto
key)And here's the result: