4

I would like to limit the rows in \pgfplotstabletypeset to the last N rows. I can skip rows by doing this:

\pgfplotstabletypeset[skip rows between index={0}{4}]{file.data}

But this only works if I know the total row count in advance. As the data file will grow over time I want the table to only contain the last, let's say 12 rows. Truncating the data file is not an option as it is also used in a pgfplot where all rows are relevant.

Is there a way to calculate the second parameter to skip rows between index based on the total number of rows from the file?

Fladi
  • 371
  • The first column contains a date field in the format of YYYY-MM-DD. Would a sequential ID help? – Fladi Oct 18 '11 at 10:22

1 Answers1

9

Here's a new style called print last that can be used to print only the last couple of rows of a table. You can specify the number of rows to be printed using the argument to print last (so print last=3 will print the last three rows of a table). If you don't supply an option, just the last line will be printed.

The style works using the row predicate, which allows us to specify a chunk of code that is executed for each line in the table, and if \pgfplotstableuserowfalse is executed within that code chunk, the line will be ignored. During the execution of the code, the total number of rows is available as \pgfplotstablerows.

Here's an example containing the style:

\documentclass{article}
\usepackage{pgfplotstable}
\usepackage{pgfcalendar} % For the date column
\usepackage{filecontents} % To be able to include the data in the .tex file

\begin{filecontents}{testdata.dat}
2011-01-01 5 7.1
2011-02-01 3 8.2
2011-03-01 4 9.1
2011-04-01 2 3.5
2011-05-01 3 9.2
2011-06-01 7 1.1
2011-07-01 7 4.8
2011-08-01 6 2.6
2011-09-01 2 2.7
2011-10-01 5 15.3
2011-11-01 6 4.1
2011-12-01 7 2.2
\end{filecontents}

\begin{document}
%% The interesting bit starts
\pgfkeys{
    /pgfplots/table/print last/.style={
        row predicate/.code={
            % Calculate where to start printing, use `truncatemacro` to get an integer without .0
            \pgfmathtruncatemacro\firstprintedrownumber{\pgfplotstablerows-#1} 
            \ifnum##1<\firstprintedrownumber\relax
                \pgfplotstableuserowfalse
            \fi
        }
    },
    /pgfplots/table/print last/.default=1
}

\pgfplotstabletypeset[
    print last=4,
    columns/0/.style={
        column type=r,
        date type={\monthname\ \year} % Nice date printing
    },
    columns/2/.style={
        dec sep align % Nice number alignment
    }
]{testdata.dat}
\end{document}
Jake
  • 232,450