0

I am trying to draw a grid of nodes, where each node has a different color:

I learnt how to draw a grid of nodes from the solution to: TikZ: Using Loop to Draw Grid of Nodes

This gives the grid below. How can I now have each node be a particular color?

enter image description here

Thanks a lot for your help!

2
2

Here is a proposal that works for arbitrary integers. The color is unique and set by \definecolor{mycol}{RGB}{\myr,100,\myb}. If you want different colors, you need to adjust this bit of code.

\documentclass[tikz,border=3mm]{standalone}
\tikzset{pics/colored grid/.style={code={
\pgfmathtruncatemacro{\mymod}{0.5+sqrt(#1)}
\pgfmathtruncatemacro{\mymmod}{\mymod+ifthenelse(#1>\mymod*\mymod,1,0)}
\draw (0,0) grid (\mymod-1,1-\mymmod);
\foreach \XX in {1,...,#1}
 {\pgfmathtruncatemacro{\myr}{mod(\XX-1,\mymod)*255/(\mymod-1)}
 \pgfmathtruncatemacro{\myb}{int((\XX-1)/\mymod)*255/(\mymmod-1)}
 \definecolor{mycol}{RGB}{\myr,100,\myb}
 \path ({mod(\XX-1,\mymod)},{-int((\XX-1)/\mymod)}) 
    node[circle,draw,text width={width("11")},align=center,
    fill=mycol]{\XX};}
}}}
\begin{document}
\begin{tikzpicture}
 \path (0,0) pic{colored grid=24} (6,0) pic{colored grid=25}
 (0,-6) pic{colored grid=33};
\end{tikzpicture}
\end{document}

enter image description here

1
  • Thanks for your help, I was able to fashion a solution based on your answer and the other comments. – nodeBeginner Sep 30 '19 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.