Add text within tikz rectangle node

You just have to add a node at \x/2:

enter image description here

\documentclass{article}

% \usepackage{xcolor}% TikZ already loads xcolor
\usepackage{tikz}

\definecolor{high}{rgb}{0.89, 0.26, 0.2}
\definecolor{med}{rgb}{1.0, 0.65, 0.0}
\definecolor{low}{rgb}{0.98, 0.93, 0.36}

\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\foreach  \l/\x/\c/\stuff[count=\y] in {%
  A/6/high/text for everyone!,
  B/4/med/more text,
  C/2/low/some text}
{%
  \node [left] at (0,\y) {\l};
  \draw [fill=\c] (0,\y-.4) rectangle (\x,\y+.4);
  \node [anchor=center] at (\x/2,\y) {\stuff};
}
\end{tikzpicture}
\end{figure}
\end{document}

Tikz defines a rectangle by two vertices of one of its diagonals, just place the node midway.

By adding a node in the middle of the path that traces the rectangle, we find exactly its center:

rectangle-midway

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\draw(0,0)rectangle(4,2)node[midway,blue]{S};
\draw[densely dotted, red](0,0)--(4,2);
\draw[densely dotted,red](0,2)--(4,0);
\end{tikzpicture}
\end{document}

Your code becomes:

 \documentclass{article}

    \usepackage{xcolor}
    \usepackage{tikz}

    \definecolor{high}{rgb}{0.89, 0.26, 0.2}
    \definecolor{med}{rgb}{1.0, 0.65, 0.0}
    \definecolor{low}{rgb}{0.98, 0.93, 0.36}

    \begin{document}
    \begin{figure}
    \centering
    \begin{tikzpicture}
    \foreach  \l/\x/\c[count=\y] in {A/6/high, B/4/med, C/2/low}
    {\node[left] at (0,\y) {\l};
    \draw[fill=\c] (0,\y-.4) rectangle (\x,\y+.4)node[midway]{\c};}
    \end{tikzpicture}
    \end{figure}
    \end{document}

the result is:

rectangle-midway


Another way :

\documentclass{article}

\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{positioning}

\definecolor{high}{rgb}{0.89, 0.26, 0.2}
\definecolor{med}{rgb}{1.0, 0.65, 0.0}
\definecolor{low}{rgb}{0.98, 0.93, 0.36}

\begin{document}
\begin{figure}
  \centering
  \begin{tikzpicture}
    \foreach  \l/\x/\c[count=\y] in {A/6cm/high, B/4cm/med, C/2cm/low}
    {
      \node[name=left-\l] at (0,\y) {\l};
      \node[fill=\c, minimum width=\x, right=(.2cm of left-\l)] at (0,\y) {\c};
    }
    \end{tikzpicture}
  \end{figure}
\end{document}

enter image description here

Tags:

Tikz Pgf