绘制彩色矩形定长位串序列

绘制彩色矩形定长位串序列

以下代码将绘制长度为 2 的位串序列:

\documentclass[tikz]{standalone}
\usetikzlibrary{chains}
\begin{document}
\begin{tikzpicture}[
  2-bin helper/.code 2 args={#1 #2},
  2-bin 00/.style={fill=cyan!50!green!50},
  2-bin 10/.style={fill=green!50!yellow},
  2-bin 01/.style={fill=red},
  2-bin 11/.style={fill=black, text=white},
  start chain=going right,
  node distance=.1em, inner xsep=.1em, % A is the widest character:
  every on chain/.append style={text width=width("A"), align=center}]
\sffamily
\node[every on chain] at (-5mm,0) {A B};
\foreach \binary in {10,01,10,01,10,01,10,01,00,00,00,00,00,00,00,11}
  \node[on chain, 2-bin \binary] {\tikzset{2-bin helper/.expand once=\binary}};
\end{tikzpicture}
\end{document}

我该如何修改它来绘制长度为 3 的位串?

答案1

shapes.multipartZ 库和ifthen包:

\documentclass[tikz]{standalone}
\usetikzlibrary{chains,
                shapes.multipart}
\usepackage{ifthen}

\begin{document}
    \begin{tikzpicture}[
node distance = 1 pt,
  start chain = going right,
  mpnv/.style args = {#1/#2/#3}{% multi part node vertical  % <---
        rectangle split, rectangle split parts=3,
        minimum width=1em,  inner ysep=1pt, 
        font = \sffamily,
        node contents = {\nodepart{one}  #1   
                         \nodepart{two}  #2
                         \nodepart{three}#3},  
        on chain},
E/.style = {fill=red!30},
O/.style = {fill=cyan!30}
                        ]
\node[mpnv=A/B/C];
\foreach \i/\j/\k  [count=\m] in  {0/0/0, 0/0/1, 0/1/0, 0/1/1, 1/0/0, 1/0/1, 1/1/0, 1/1/1, 
                                   0/0/0, 0/0/1, 0/1/0, 0/1/1, 1/0/0 } % whatever is here
{
\ifnum\m>8
    \node[fill=olive, mpnv=\i/\j/\k];
\else
\ifthenelse{\isodd{\m}}
   {\node[O, mpnv=\i/\j/\k]}
   {\node[E, mpnv=\i/\j/\k]};
\fi 
}

    \end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

另一个解决方案是matrix

\documentclass[tikz]{standalone}
\usetikzlibrary{matrix}

\begin{document}
    \begin{tikzpicture}[
        red column/.style={column #1/.append style={nodes={fill=red}}},
        green column/.style={column #1/.append style={nodes={fill=green}}},
        black column/.style={column #1/.append style={nodes={fill=black, text=white}}},]
    \matrix[matrix of nodes, column sep=2pt,
        nodes={minimum height=5mm, anchor=center, font=\sffamily},
        red column/.list={2,...,6}, green column/.list={9,11},
        black column/.list={8}]
        {A & 0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 1\\
         B & 0 & 0 & 1 & 1 & 0 & 0 & 1 & 1 & 0 & 0 & 1 & 1 & 0\\
         C & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0\\};
    \end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容