13

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?

David Carlisle
  • 757,742

2 Answers2

18

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}
David Carlisle
  • 757,742
Caramdir
  • 89,023
  • 26
  • 255
  • 291
5

You can put each node inside a save box, and then it will work:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}

\newsavebox{\speciesone}
\sbox{\speciesone}{
\begin{tabular}{c c c}
  \multicolumn{3}{c}{{Species 1}} \tabularnewline
  \colorbox{red}{G1a} & \colorbox{blue}{G2a} &
  \colorbox{green}{G3} \tabularnewline
  \colorbox{blue}{G1b} & \colorbox{red}{G2b} & 
  \end{tabular}
  }

\begin{document}
\begin{tikzpicture}
\matrix [matrix of nodes] {
\node (species1) [shape=rectangle,draw] {\usebox{\speciesone}};\\
};
\end{tikzpicture}


\end{document}
David Carlisle
  • 757,742
Alan Munn
  • 218,180