Tikz PGF – Using \foreach to Draw Multiple Line Segments

tablestikz-pgf

I was wondering (I know there is) a simpler way of creating a table using Tikz. I am currently make columns every x units by hand. Is there a way I can do this using foreach command? As you can see it takes alot of time. Thank you for the help. This section of code is from a larger code.

\documentclass{report}
\usepackage{pgfplots}
\usepackage{amsmath}
\usepackage{tikz}
\begin{tikzpicture}
\begin{scope}[shift={(0,-12)}]
\draw (0.2,22)--(17.8,22)--(17.8,17.5)--(0.2,17.5)--cycle;
\draw (0.2,22)--(17.8,22)node[midway,sloped,draw,rectangle,fill=red!15]{Example 3};
\path (0.2,21)node[anchor=west]{\small The table above gives values of a function  $f$  at selected values of  $x$ . Which of the following conclusions is supported by};
\path (0.2,20.5)node[anchor=west]{\small the data in the table?};
\draw (3.4,20)--(14.8,20)--(14.8,19)--(3.4,19)--cycle;
\draw (4.666,20)--(4.666,19);
\draw (5.9332,20)--(5.9332,19);
\draw (7.1999,20)--(7.1999,19);
\draw (8.45992,20)--(8.45992,19);
\draw (9.7265,20)--(9.7265,19);
\draw (10.9931,20)--(10.9931,19);
\draw (12.2598,20)--(12.2598,19);
\draw (13.52644,20)--(13.52644,19);
\draw (14.7930,20)--(14.793,19);

\end{scope}
\end{tikzpicture}
\end{document}


Best Answer

If you really want to do this with TikZ (which I still don't understand, since you can mix a real table with TikZ drawings, but anyway), you can use matrix of nodes.

\documentclass[a4paper, 11pt]{article}
\usepackage{geometry}
\geometry{hmargin=1cm,vmargin=1cm}
\usepackage{tikz}
\usetikzlibrary{matrix}
\usepackage{lipsum}

\tikzset{
    mymat/.style={
          matrix of nodes,
          anchor=center,
          nodes=draw,nodes in empty cells,
          minimum height=10mm,
          minimum width=15mm,
          align=center,
          column sep=-\pgflinewidth
          },
    }
    
\begin{document}
 
\lipsum[1]\\

\begin{center}
    \begin{tikzpicture}
    
        \draw (0,0) rectangle (14,3);
        \node[anchor=center,draw,fill=red!15] at (7,3) {Example 3};
        \node[anchor=center,text width=13cm,align=center] at (7,2)
            {\small The table above gives values of a function  $f$  at selected values of  $x$ . Which of the following conclusions is supported by the data in the table?};       
        \matrix[mymat] (m) at (7,0.8)
                {
                 & & & & & & & & \\
                };
    
    \end{tikzpicture}
\end{center}
    
\end{document}

table with matrix of nodes