3

I'd like to make a histogram with pgfplots showing percentages on the y-axis instead of the number of points falling into the bins, like so (the example is taken from the manual):

\documentclass[11pt]{scrartcl}
\usepackage{tikz}
\usepackage{pgfplots}
\usepgfplotslibrary{statistics}

\usepackage{filecontents}
\begin{filecontents*}{histdata.dat}
  1
  2
  1
  5
  4
  10
  7
  10
  9
  8
  9
  9
\end{filecontents*}

\begin{document}
\begin{tikzpicture}[]
  \begin{axis}[
    ybar interval,
    xticklabel={\pgfmathprintnumber\tick--\pgfmathprintnumber\nexttick},
    yticklabel={\pgfmathparse{(\tick/12)*100}\pgfmathprintnumber{\pgfmathresult}\%},
    yticklabel style={
      /pgf/number format/.cd,
      fixed, precision=0,
      /tikz/.cd
    },
    ]
    \addplot+ [hist={bins=3}]
    table [y index=0] {histdata.dat};
  \end{axis}
\end{tikzpicture}
\end{document}

However, I can only calculate the percentages if I know the number of total data values, in this case 12.

Is there a way in pgfplots or (lua)latex in general to count the number of data values, meaning the number of rows in the data file?

Florian
  • 515

1 Answers1

6

pgfplotstable has a macro for that:

\pgfplotstablegetrowsof{histdata.dat}
\edef\NRows{\pgfplotsretval} % save result to \NRows

Complete example:

\documentclass[11pt]{scrartcl}
\usepackage{pgfplotstable} % loads pgfplots which loads tikz
\usepgfplotslibrary{statistics}

\usepackage{filecontents}
\begin{filecontents*}{histdata.dat}
  1
  2
  1
  5
  4
  10
  7
  10
  9
  8
  9
  9
\end{filecontents*}

\pgfplotstablegetrowsof{histdata.dat}
\edef\NRows{\pgfplotsretval}
\begin{document}



\begin{tikzpicture}[]
  \begin{axis}[
    ybar interval,
    xticklabel={\pgfmathprintnumber\tick--\pgfmathprintnumber\nexttick},
    yticklabel={\pgfmathparse{(\tick/\NRows)*100}\pgfmathprintnumber{\pgfmathresult}\%},
    yticklabel style={
      /pgf/number format/.cd,
      fixed, precision=0,
      /tikz/.cd
    },
    ]
    \addplot+ [hist={bins=3}]
    table [y index=0] {histdata.dat};
  \end{axis}
\end{tikzpicture}

\end{document}
Torbjørn T.
  • 206,688