10

How can I generate a step-pyramid in LaTeX?

I'm guessing I would use a graph module to centre chart bars...

I want to be able to select the length of each "row" of the pyramid, and show that number next to it, like so: Mockup

Thanks for all suggestions

4
  • Those bars don't look centred. Should we assume that they are?
    – huon
    May 4, 2012 at 7:29
  • Yes, rocked this up in paint. Also assume that it isn't to scale!
    – A T
    May 4, 2012 at 7:38
  • @AT Shouldn't the 20 be 21?
    – yannisl
    May 4, 2012 at 8:23
  • -_- < "Not to scale"
    – A T
    May 4, 2012 at 11:23

2 Answers 2

13

I suggest you use TikZ and a \foreach loop

\documentclass{article}

\usepackage{tikz}
\usepackage{xcolor}

\definecolor{barcolor}{named}{gray}
\definecolor{barborder}{named}{red}

\newcommand{\barheight}{0.5cm}

\newcommand{\pyramid}[1]{%
    \begin{tikzpicture}[x=0.25cm]
        \foreach \b [count=\n] in {#1} {
            \draw [barborder,fill=barcolor]
                (-0.5*\b,{(\n-1)*\barheight}) rectangle (0.5*\b,\n*\barheight);
            \node at (-0.5*\b,\n*\barheight-0.5*\barheight) [left] {\b};
        }
    \end{tikzpicture}
}


\begin{document}
    \pyramid{28,26,17,7}
\end{document}

result

Usage/Notes

  • Us it with \pyramid{<values>} separate the values with commas , and sort the descending.

  • Set the colors barcolor and barborder with xcolor.

  • Change x=0.25cm to scale the image vertically.

  • Change \newcommand{\barheight}{0.5cm} to set the height of the bars.

  • You may want to add a font setting in the node like this

    \node at (...) [left,font=\small] {\b};
    
  • It is also possible to align the numbers above each other.

    \newcommand{\Pyramid}[1]{%
       \begin{tikzpicture}[x=0.25cm]
        \foreach \b [count=\n] in {#1} {
                    % Store the first value in the list
            \ifnum\n=1\relax\xdef\firstbarwidth{\b}\fi
            \draw [barborder,fill=barcolor]
                (-0.5*\b,{(\n-1)*\barheight}) rectangle (0.5*\b,\n*\barheight);
            \node at (-0.5*\firstbarwidth,\n*\barheight-0.5*\barheight) [left] {\b};
        }
       \end{tikzpicture}
    }
    

    result 2

    (I changed the macro name to \Pyramid, with an uppercase P, so you can compare them in one document.)

0
8

Minimalistic non-TikZ solution, with a bit of color and shade. Adjust to suit taste.

enter image description here

\documentclass{article}
\usepackage{xcolor}
\newcounter{ctr}
\newcounter{ctra}
\setcounter{ctra}{7}
\newlength\rwidth
\setlength\rwidth{50pt}
\fboxsep0pt
\fboxrule0pt
\begin{document}
\begin{center}
\loop
\ifnum\thectr<4
\fbox{\thectra}\colorbox{gray}{\color{olive}\rule{\the\rwidth}{30pt} }\\[-1.0pt]
\stepcounter{ctr}
\addtocounter{ctra}{7}
  \setlength\rwidth{\dimexpr\the\rwidth+30pt\relax}
\repeat
\end{center}
\end{document}
0

You must log in to answer this question.

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