TikZ-PGF – How to Create a Pyramid Hierarchy in TikZ

diagramsgraphicstikz-pgf

I want to create a pyramid hierarchy in tikz with smooth sides (unlike this step-pyramid) and place text in each level. Shown below is how I am currently doing this, is there a better way?

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{figure}[!h]
\centering
\begin{tikzpicture}[scale=0.73]

\def \h {9};
\def \f {.7};

\foreach \y in  {0,1,2,3,4,5,6} {
    \def \w { \h*\f-\y*\f };
    \def \v { \y*\f-\h*\f };
    \draw (\v,\y) -- (\w,\y);
}

\draw (-\h*\f,0)  -- (0,\h);
\draw (\h*\f,0)  -- (0,\h);

\node at (0,0) [above] {G};
\node at (0,1) [above] {F};
\node at (0,2) [above] {E};
\node at (0,3) [above] {D};
\node at (0,4) [above] {C};
\node at (0,5) [above] {B};
\node at (0,6) [above] {A};
\end{tikzpicture}
\end{figure}
\end{document}

enter image description here

Best Answer

Here is a simplification using the tikz intersections library to cut down on brute-force calculation:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{intersections}
\begin{document}

\begin{tikzpicture}
\coordinate (A) at (-5,0) {};
\coordinate (B) at ( 5,0) {};
\coordinate (C) at (0,7) {};
\draw[name path=AC] (A) -- (C);
\draw[name path=BC] (B) -- (C);
\foreach \y/\A in {0/G,1/F,2/E,3/D,4/C,5/B,6/A} {
    \path[name path=horiz] (A|-0,\y) -- (B|-0,\y);
    \draw[name intersections={of=AC and horiz,by=P},
          name intersections={of=BC and horiz,by=Q}] (P) -- (Q)
        node[midway,above] {\A};
}
\end{tikzpicture}
\end{document}

Notice the combination of level numbers and labels as in Gonzalo's comment.

sample code output

Here is another solution using the tikz calculations library:

\foreach \y/\A in {0/G,1/F,2/E,3/D,4/C,5/B,6/A} {
    \draw ($(A)!\y/7!(C)$) -- ($(B)!\y/7!(C)$)
        node[midway,above] {\A};
}

The coordinate ($(A)!\y/7!(C)$) is \y/7 of the way between the coordinates A and C. The advantage here is total DRY: Change any of the coordinates A, B, or C, and the pyramid will transform accordingly.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}

\begin{tikzpicture}
\coordinate (A) at (-5,0) {};
\coordinate (B) at ( 5,1) {};
\coordinate (C) at (0,3) {};
\draw (A) -- (C);
\draw (B) -- (C);
\foreach \y/\A in {0/G,1/F,2/E,3/D,4/C,5/B,6/A} {
    \draw ($(A)!\y/7!(C)$) -- ($(B)!\y/7!(C)$) node[midway,above] {\A};
}
\end{tikzpicture}
\end{document}

sample code output