将表格放入矩阵内的节点中

将表格放入矩阵内的节点中

我有一张图片,其中每个节点看起来都像这样:

\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}
};

节点看起来很好,但是当我将它们全部放入一个matrix节点以正确对齐它们时,tabular节点内部的 s 都搞砸了,并且出现如下错误:

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

有什么办法可以让它工作吗?

答案1

问题在于 TikZ 需要使&等效于\pgfmatrixnextcell,这会干扰&作为表格单元格分隔标记的正常功能。幸运的是,TikZ 包含一个ampersand 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}

答案2

您可以将每个节点放入一个保存框中,然后它就可以工作了:

\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}

相关内容