Plots | How to select first n rows of data to plot?

Here is a style that allows you to select the rows N through M (inclusive, starting at 0) by specifying select coords between index={N}{M}. To select the first N points, you would specify select coords between index={0}{N-1}.

It is based on the explanation of the filter point style in the pgfplots manual. There is also an oppposite style that is already part of pgfplots: skip coords between index={N}{M}discards all points that are inside the range N to M.

\documentclass[tikz]{standalone}
\usepackage{pgfplots}

% Style to select only points from #1 to #2 (inclusive)
\pgfplotsset{select coords between index/.style 2 args={
    x filter/.code={
        \ifnum\coordindex<#1\def\pgfmathresult{}\fi
        \ifnum\coordindex>#2\def\pgfmathresult{}\fi
    }
}}

\usepackage{filecontents}
\begin{filecontents}{data.txt}
 X    Y
-3    9      %  0 left out
-2    4      %  1 plotted
-1    1      %  2 plotted
-0.5  0.25   %  3 plotted
 0    0      %  4 plotted
 0.5  0.25   %  5 plotted
 1    1      %  6 left out
 2    4      %  7 left out
 3    9      %  8 left out
\end{filecontents}

\begin{document}
    \begin{tikzpicture}
        \begin{axis}
        \addplot [select coords between index={1}{5}] table {data.txt};
        \end{axis}
    \end{tikzpicture}
\end{document}

Image: Designed by jcomp/Freepik
Source text: tex.stackexchange.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: