TikZ – Drawing Grids Filled with Random Colors and Connecting Them

colorgridsnode-connections

What I'm trying to do is to draw to 4 x 4 grids side-by-side to represent the concept of bootstrap, from statistics.

So, what I would like to do is to draw them and fill each cell of each grid with a random color chosen from a predefined set of colors.

After that, I would like to connect the grids with an arrow centered on the y middle of them with and the x positioned at the right and left border of them, respectively.

This is an example of what I would like to achieve:

enter image description here

This is my current approach:

\documentclass[11pt,a4paper]{article}

\usepackage{tikz}

\begin{figure}[htb]
\begin{tikzpicture}[scale=.7]

    \begin{scope}
        \draw (0, 0) grid (4, 4);
        \coordinate (input);
    \end{scope}

    \begin{scope}[xshift=7cm] 
        \draw (0, 0) grid (4, 4);
        \coordinate (output);
    \end{scope}  

    \draw[-latex, thick, red!80] (input) -- (output) node [pos=0.5,above,font=\footnotesize] {output};

\end{tikzpicture}
\end{figure}

\end{document}

However, I'm far from what I would like:

enter image description here

How should I proceed?

Thank you.

Best Answer

I would suggest you use the to syntax instead of the -- for connecting the squares. For coloring the squares you can define a list of colors via \pgfmathdeclarerandomlist:

enter image description here

Notes:

  • I used tikz's calc library to get the midpoint of the squares.

Code:

\documentclass[11pt,a4paper]{article}

\usepackage{tikz}
\usetikzlibrary{calc}

\pgfmathdeclarerandomlist{MyRandomColors}{%
    {red}%
    {red!25}%
    {magenta}%
    {magenta!25}%
    {olive}%
    {olive!25}%
    {brown}%
    {brown!10}%
    {violet}%
    {violet!25}%
    {gray}%
    {purple}%
    {yellow}%
    {orange}%
    {orange!25}%
    {cyan}%
    {green}%    
}%

\newcommand*{\GridSize}{4}

\newcommand*{\ColorCells}{%
    \foreach \y in {1,...,\GridSize} {
        \foreach \x in {1,...,\GridSize} {
            \pgfmathrandomitem{\RandomColor}{MyRandomColors} 
            \draw [fill=\RandomColor, fill opacity=0.4, draw=none, ultra thick] 
                (\x-1,\y-1) rectangle (\x,\y);
        }%
    }%
}%

\listfiles
\begin{document}
\begin{tikzpicture}[scale=.7]

    \begin{scope}[thick]
        \ColorCells
        \draw (0, 0) grid (\GridSize, \GridSize);
        \coordinate (input);
    \end{scope}

    \begin{scope}[thick, xshift=7cm] 
        \ColorCells
        \draw (0, 0) grid (\GridSize, \GridSize);
        \coordinate (output);
    \end{scope}  

    \draw[-latex, ultra thick, red!80] 
        ($(input)+(2.5,2.5)$) to[out=0, in=180] 
            node [pos=0.5,sloped, above,font=\footnotesize] {output}
        ($(output)+(1.5,1.5)$) 
            ;

\end{tikzpicture}
\end{document}
Related Question