[Tex/LaTex] How to force nodes to have the same size in tikz matrices

matricesnodestikz-matrixtikz-pgf

Is there some intelligent way to have several tikz nodes have the same height and width? Consider the following example with output below.

I'd like every node in each row to have the same height equal to the height of the tallest node and every node in each column to have the same width equal to the width of the widest node.

In the example below each node in the third row has a different height. In the first two rows the heights are forced to be equal using \vphantom. There must be a more intelligent way to do this. Any ideas? What about the columns (they contain identical nodes, but they would not normally)?

I don't want to hard-code a minimum width+height.

Thank you!

J.

\documentclass{minimal}

\usepackage[svgnames]{xcolor}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
[every node/.style={anchor=base}]
\matrix [draw=red]
{
\node[fill=Orange] {a\vphantom{Xg}}; & \node[fill=Green] {X\vphantom{ag}}; & \node[fill=LightGreen] {\vphantom{aX}g}; \\
\node[fill=Yellow] {a\vphantom{Xg}}; & \node[fill=Cyan] {X\vphantom{ag}}; & \node[fill=Magenta] {\vphantom{aX}g}; \\
\node[fill=Purple] {a}; & \node[fill=LightBlue] {X}; & \node[fill=Aquamarine] {g}; \\
};
\end{tikzpicture}
\end{document}


Using text depth and text height, you can control the total height for the nodes; text width gives you control over the width (there's also a minimum size key which could be used):

\documentclass{article}
\usepackage[svgnames]{xcolor}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}[every node/.style={anchor=base,text depth=.5ex,text height=2ex,text width=1em}]
\matrix [draw=red]
{
\node[fill=Orange] {a}; & \node[fill=Green] {X}; & \node[fill=LightGreen] {g}; \\
\node[fill=Yellow] {a}; & \node[fill=Cyan] {X}; & \node[fill=Magenta] {g}; \\
\node[fill=Purple] {a}; & \node[fill=LightBlue] {X}; & \node[fill=Aquamarine] {g}; \\
};
\end{tikzpicture}
\end{document}


As percusse mentions in his comment, a matrix of nodes (requires the matrix library) could be more useful here; it simplifies the code and also gives you a nodes in empty cells key to deal with the case of cells without explicit text:

\documentclass{article}
\usepackage[svgnames]{xcolor}
\usepackage{tikz}
\usetikzlibrary{matrix}

\begin{document}
\begin{tikzpicture}[every node/.style={anchor=base,text depth=.5ex,text height=2ex,text width=1em}]
\matrix [matrix of nodes,draw=red,nodes in empty cells]
{
|[fill=Orange]| a & |[fill=Green]| X & |[fill=LightGreen]| \\
|[fill=Yellow]| a & |[fill=Cyan]| & |[fill=Magenta]| g \\
|[fill=Purple]| & |[fill=LightBlue]| X & |[fill=Aquamarine]| g \\
};
\end{tikzpicture}
\end{document}