2

I currently have a 2x2 grid using this code:

\begin{center}
\begin{tikzpicture}
\draw (0,0) grid (2,2);

\end{tikzpicture}
\end{center}

I was wondering how I would be able to color for instance the top-left square black and the bottom-right square green.

Thanks!

4
  • 2
    \documentclass[tikz,border=3mm]{standalone} \begin{document} \begin{tikzpicture} \fill (0,1) rectangle ++ (1,1); \fill[green] (1,0) rectangle ++ (1,1); \draw (0,0) grid (2,2); \end{tikzpicture} \end{document}
    – user194703
    Commented May 7, 2020 at 22:10
  • Thanks for your help!
    – Richard
    Commented May 7, 2020 at 22:35
  • @Schrödinger'scat Can you make your suggestion as an answer? please, so that it will help for other users, who may needs the same requirement....
    – MadyYuvi
    Commented May 8, 2020 at 5:40
  • 2
    @MadyYuvi Done, thanks!
    – user194703
    Commented May 8, 2020 at 5:59

1 Answer 1

4

To fill a rectangle, you only need to say

\fill[<color>] (<corner>) rectangle (<diagonally opposite corner>);

so the TikZ code for the question is as simple as

\fill (0,1) rectangle ++ (1,1); 
\fill[green] (1,0) rectangle ++ (1,1); 
\draw (0,0) grid (2,2); 

As you can see, we add three different paths. Note also that we draw the grid last.

Sometimes it might be worthwhile to have everything in one path macro. Then one can add the filled rectangles either via nodes or pics, among other things. If one does that, and wants the grid on top, one may want to use the behind path option. Here is a complete code with a few examples.

\documentclass[tikz,border=3mm]{standalone} 
\begin{document} 
\begin{tikzpicture} 
\begin{scope}[local bounding box=L]
 \fill (0,1) rectangle ++ (1,1); 
 \fill[green] (1,0) rectangle ++ (1,1); 
 \draw (0,0) grid (2,2); 
\end{scope} 
%
\begin{scope}[xshift=3cm,local bounding box=M,
    block/.style={minimum size=1cm,fill=#1,anchor=south west,inner sep=0pt,
    behind path}]
 \draw (0,1) node[block=black]{}
  (1,0) node[block=green]{}
 (0,0) grid (2,2); 
\end{scope} 
%
\begin{scope}[xshift=6cm,local bounding box=R,
    pics/block/.style={code={\path[pic actions] (0,0) rectangle ++ (1,1);}}]
 \draw[behind path] (0,1) pic[fill]{block}
  (1,0) pic[fill=green]{block}
 (0,0) grid (2,2); 
\end{scope} 
%
\path[nodes={text depth=0.25ex,above,font=\sffamily}] 
    (L.north) node{fill}
    (M.north) node{node}
    (R.north) node{pic};
\end{tikzpicture} 
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .