# Numbered and coloured grid using Tikz

I'm trying to create a large grid with 1,000 entries, similar to what is in this link:

TikZ (finite) grid with character in each cell

I want each entry to be filled with consecutive numbers and set the background colour independently in each one. IS there a quick way to generate this list without inputing each entry manually?

• Welcome to TeX.SE! I would recommend you to have a look at for loops in TikZ/PGF. – TeXnician Feb 7 '17 at 10:45

## 2 Answers

Something like this? (with credits to zeroth and samcarter)

\documentclass[tikz, border=2mm]{standalone}

\begin{document}
\begin{tikzpicture}[scale=1]
\foreach \y [count=\ny from 0] in {0.5,1.5,...,49.5} {
\foreach \x [count=\nx, evaluate=\x as \num using int(\nx+10*\ny)] in {0.5,1.5,...,19.5} {
\pgfmathsetmacro{\R}{random(0,10000)/10000}%
\pgfmathsetmacro{\G}{random(0,10000)/10000}%
\pgfmathsetmacro{\B}{random(0,10000)/10000}%
\definecolor{MyColor}{rgb}{\R,\G,\B}%
\node[fill=MyColor,inner sep=0.1cm,outer sep=0pt,anchor=center, minimum size=1cm] at (\x,-\y) {\num};
}
}
\end{tikzpicture}
\end{document}


Complete result:

A detail:

For comparison here's a slightly different approach done in Metapost using the luamplib wrapper library. Compile with lualatex.

\RequirePackage{luatex85}
\documentclass[border=5mm]{standalone}
\usepackage{luamplib}
\begin{document}
\mplibtextextlabel{enable}
\begin{mplibcode}
beginfig(1);
numeric rows, cols, u, v;
% how big is the grid?
rows = 13;
cols = 8;
% horizontal and vertical units
u = 13mm;
v =  8mm;
% a nice unit box scaled slightly smaller so we get a margin
path box;
box = unitsquare
shifted -(1/2,1/2) % shifted so it's centred on (0,0)
xscaled (u-1mm)
yscaled (v-1mm);
% define all the colors
color shade[];
% give them all a default color,
for i=1 upto (rows*cols):
shade[i] = .9[blue, white];
endfor
% explicitly define colors for what ever cells
shade[1]  := 1/2[red,white];
shade[21] := 2/3[blue,white];
shade[94] := 2/3[red+1/2green,white];
% etc....

numeric n;
for c = 1 upto cols:
for r = 1 upto rows:
n := c + (r-1)*cols;
fill box shifted (c*u,r*v) withcolor shade[n];
draw box shifted (c*u,r*v);
label(decimal n, (c*u,r*v));
endfor
endfor
endfig;
\end{mplibcode}
\end{document}