[Tex/LaTex] Putting a tabular in a node within a matrix

matricesnodestablestikz-pgf

I have a picture in which each of the nodes looks something like this:

\node (species1) [shape=rectangle,draw] {
  \begin{tabular}{c c c}
  \multicolumn{3}{c}{{Species 1}} \\
  \colorbox{red}{G1a} & \colorbox{blue}{G2a} &
  \colorbox{green}{G3} \\
  \colorbox{blue}{G1b} & \colorbox{red}{G2b} & 
  \end{tabular}
};

The nodes look fine, but when I put them all into a matrix node to align them properly, the tabulars inside the nodes are all screwed up and I get errors like this one:

Extra alignment tab has been changed to \cr. ...{G1} & \colorbox{blue}{G2a} &
\colorbox (followed by: {green!50}{G3})

Is there are way to make this work?

Best Answer

The problem is that TikZ needs to make & equivalent to \pgfmatrixnextcell, which interferes with the normal functioning of & as a table cell separation marker. Fortunately, TikZ includes the ampersand replacement option that lets you choose any other macro for matrix cell separation instead of &. The following example uses \& as replacement:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
    \matrix[ampersand replacement=\&] {
        \node (species1) [shape=rectangle,draw] {
            \begin{tabular}{c c c}
                \multicolumn{3}{c}{{Species 1}} \\
                \colorbox{red}{G1a} & \colorbox{blue}{G2a} & \colorbox{green}{G3} \\
                \colorbox{blue}{G1b} & \colorbox{red}{G2b} & 
            \end{tabular}
        };
        \& 
        \node {b}; \\
        \node {c}; \& \node {d}; \\
};
\end{tikzpicture}

\end{document}