[Tex/LaTex] Define different ranges for different data sets when plotting from a file or table

pgfplots

I would like to make a plot of several data sets that are stored in a text file (tab-separated). Is there a way of defining the x-range for which some (not all) of the data sets should be plotted? I want some data sets to plot fully, and others only in specified ranges.

Consider the following example:

The table:

x B C D

1 3 4 5

2 4 6 3

3 4 7 4

4 5 7 2

should be plotted so that all four values of columns B and C are plotted against the x values, but only the values for which x is in the range [2,3] should be plotted for column D.

In other words, I want to use \addplot three times in the same axis environment, and define the x-range separately for each data set.

The condition cannot be the index. I need to use this for large data files, for which I do not know the indices of the data points I need. Hence, the input to define the points to plot must be an x interval.

Best Answer

You can use the key restrict x to domain=<start>:<end>, which installs a filter that removes all data points outside the specified range:

\documentclass{article}

\usepackage{pgfplots}

\pgfplotstableread{
x B C D
1 3 4 5
2 4 6 3
3 4 7 3
4 5 7 2
}\datatable

\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot table [y=B] {\datatable};
\addplot table [y=C] {\datatable};
\addplot +[restrict x to domain=2:3] table [y=D] {\datatable};
\end{axis}
\end{tikzpicture}
\end{document}
Related Question