[Tex/LaTex] labeling edges in tikz

labelstikz-pgf

I have the following graph, where I want to label the edges. Is there a way I can integrate this in to the draw command?

{
\begin{figure}
\begin{center}
\begin{tikzpicture}[every node/.style={circle, draw, scale=.8, fill=gray!50}, scale=1.0, rotate = 180, xscale = -1]

\node (1) at ( 2.55, 3.0) {1};
\node (2) at ( 3.87, 0.92) {2};
\node (3) at ( 6.85, 0.92) {3};
\node (4) at ( 8.17, 3.0) {4};
\node (5) at ( 6.85, 5.0) {5};
\node (6) at ( 3.87, 5.0) {6};
\node (7) at ( 10.2, 3.0) {7};
\node (8) at ( 12.2, 3.0) {8};

\draw (2) -- (1);
\draw (3) -- (2);
\draw (4) -- (3);
\draw (7) -- (4);
\draw (8) -- (7);
\draw (6) -- (1);
\draw (5) -- (6);
\draw (4) -- (5);

\end{tikzpicture}
\caption{Weight 2}
\label{fig:wt2}
\end{center}
\end{figure}
}

Best Answer

you can add a new node to your draw command to create a label:

\draw (Point1) -- (Point2) node [<position>, fill=white] {Label Text};

The position Parameter can be one of:

  • midway
  • near end
  • near start

Also you can set the label above or below the connector created by the draw command. Herefore you can use

  • above
  • above=10pt
  • below
  • below=10pt
  • ...

If you want to create many labels in your drawing i recommend to create a label style you assign to each label node.

EDIT - Some more information:

If you want to play around with labels and their positions and placing them also on curved lines, use the following code:

\documentclass[border=6mm]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \x [count=\i] in {midway, at start, near start, very near start, at end, near end, very near end} {
  \draw (0,-\i) .. controls ++(1,1) and ++(-1,1) .. ++(4,0) node [\x, sloped, fill=white] () {\x};
}
\end{tikzpicture}
\end{document}

The information can also be found in the pgfmanual on page 195