# How can I position the text within a node of a graph?

I would like to create a visualization of the Bellman-Ford algorithm. To do so, I need to add the information of the weight (number or $\infty$) and the predecessor (letter) into every node. This should look like that (done with Gimp):

How can I make that with LaTeX (Tikz)?

I am currently create my graph:

\documentclass{beamer}
\usepackage{tikz}
\usepackage{verbatim}
\usetikzlibrary{arrows,shapes}

\begin{document}
\pgfdeclarelayer{background}
\pgfsetlayers{background,main}

\begin{frame}
\tikzstyle{vertex}=[circle,fill=black!25,minimum size=20pt,inner sep=0pt]

\begin{figure}
\begin{tikzpicture}[scale=2.5, auto,swap]
% First we draw the vertices
\foreach \pos/\name in {{(0,2)/a}, {(1,2)/b}, {(2,2)/c},
{(0,1)/d}, {(1,1)/e}, {(2,1)/f},
{(0,0)/g}, {(1,0)/h}, {(2,0)/i}}
\node[vertex] (\name) at \pos {$\name$};
% Connect vertices with edges and draw weights
\foreach \source/ \dest /\weight/\style in {a/b/0/, b/c/1/, a/d/2/, e/d/5/,
b/e/3/bend right, e/b/-1/bend right, b/f/4/above, f/i/3/,
i/e/1/, g/h/1/}
\path (\source) edge[->,\style, thick] node {$\weight$} (\dest);
\end{tikzpicture}
\end{figure}
\end{frame}
\end{document}

-

You can place the text using label={[<options>]center:<text>}, where center puts the label in the middle of the "host" node, so you'll have to move it using xshift=..., yshift=... in the <options> of the label.

\documentclass{beamer}
\usepackage{tikz}
\usepackage{verbatim}
\usetikzlibrary{arrows,shapes}

\begin{document}
\pgfdeclarelayer{background}
\pgfsetlayers{background,main}

\begin{frame}
\tikzset{
vertex/.style={
circle,
fill=black!25,
minimum size=20pt,
inner sep=0pt,
text height=1ex,
text depth=1ex,
label={[weight label]center:\weight},
label={[pred label]center:\pred}
},
pred label/.style={
font=\tiny,
xshift=0.3em,
yshift=-0.8ex,
text height=1ex,
text depth=0pt
},
weight label/.style={
font=\tiny,
xshift=-0.3em,
yshift=-0.8ex,
text height=1ex,
text depth=0pt
}
}

\begin{figure}
\begin{tikzpicture}[scale=2.5, auto,swap]
% First we draw the vertices
\foreach \pos/\name/\weight/\pred in {%
{(0,2)/a/0/g},%
{(1,2)/b/$\infty$/a}%
}
\node[vertex] (\name) at \pos {$\name$};
% Connect vertices with edges and draw weights
\foreach \source/ \dest /\weight/\style in {a/b/0/}
\path (\source) edge[->,\style, thick] node {$\weight$} (\dest);
\end{tikzpicture}
\end{figure}
\end{frame}
\end{document}

-
Thank you very much! This was exactly what I was looking for. But I don't understand how this works. How would I make a single node? This does not work: \node[vertex] (a) at (0,2) {$a$, pred=b, weight=123}; – Martin Thoma Jul 20 '12 at 15:01