我正在尝试创建一个包含 1,000 个条目的大型网格,类似于此链接中的内容:
我希望每个条目都用连续的数字填充,并在每个条目中独立设置背景颜色。有没有一种快速的方法可以生成此列表,而无需手动输入每个条目?
答案1
\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}
完整结果:
一个细节:
答案2
为了进行比较,这里有一个稍微不同的方法元帖子使用luamplib
包装器库。使用 进行编译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}