3

I want to draw 50 rectangles with height 3 & breadth 1. There should be space among these rectangles. Also I want to fill with blue color for rectangle number 1,5,7,10, 16, 22, with green color for 2, 14, 35, 44,46, others with red color.

Is there any easy way using \foreach statement in Tikz? Or is there any other easy way? I tried like this:

\begin{figure}[!htb]
    \centering 
    \scalebox{0.32}{
        \begin{tikzpicture}
            
        

    \foreach \x in {0, 1, ..., 50 }
          \draw (\x,0) rectangle (\x,10);
          %\draw [draw=black] (\x,4) rectangle (0.5,0);
          %\draw (\x,0) rectangle (0.5,4);

        %\draw [Stealth-Stealth, color = blue, thin] (\x, 0.3) -- (\x, 6.8);
        
        
            
    \end{tikzpicture}
    }
    \caption{}
    
\end{figure}

2 Answers 2

7
\documentclass[tikz, border=1cm]{standalone}
\begin{document}
\begin{tikzpicture}
\foreach \x in {1,...,50}
\fill[red] (1.1*\x,3) rectangle (1.1*\x+1,0);
\foreach \x in {1,5,7,10,16,22}
\fill[blue] (1.1*\x,3) rectangle (1.1*\x+1,0);
\foreach \x in {2,14,35,44,46}
\fill[green] (1.1*\x,3) rectangle (1.1*\x+1,0);
\end{tikzpicture}
\end{document}

A stipe of 50 colored rectangles

1
  • Note that the red rectangles are drawn behind the other colors, which could give a hint of red shining through the edges dependent on the viewer. Either give the number explicitly to the list of red or use the more veracious answer by @Ignasi dependent on the use case. Feb 9, 2022 at 10:52
2

Just for fun another version with a matrix and lists of colored cells.

\documentclass[tikz, border=1cm]{standalone}
\usetikzlibrary{matrix}

\begin{document}
\begin{tikzpicture}[
    mymatrix/.style={matrix of nodes, nodes in empty cells,
        nodes={fill=red, anchor=center, minimum width=3mm, minimum height=8mm, inner sep=0pt, outer sep=0pt},
        column sep=1pt,
        },
    bluecell/.style={column #1/.style={nodes={fill=blue}}},      
    greencell/.style={column #1/.style={nodes={fill=green}}},        
    ]
\matrix[mymatrix, bluecell/.list={1,5,7,10,16,22}, greencell/.list={2,14,35,44,46}]
    {&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\\};
\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 .