4

I have seen people apply a filter to imported data before plotting with pgfplots, see grouping data in pgfplots. Is there a way to extend the approach presented there to apply multiple filters? In the MWE below I made the naive modifications to the solution given there, but it seems that only the last filter is applied: the unwanted y=1 data points are plotted too.

\documentclass{article}
\usepackage{filecontents}
\usepackage{pgfplots}

\begin{filecontents}{foo.txt}
  x y z f
  0 0 0 0
  0 0 1 1
  0 1 0 2
  0 1 1 3
  1 0 0 4
  1 0 1 5
  1 1 0 6
  1 1 1 7
  \end{filecontents}

\pgfplotsset{
  discard if not/.style 2 args={
  x filter/.code={
  \edef\tempa{\thisrow{#1}}
  \edef\tempb{#2}
  \ifx\tempa\tempb
  \else
    \def\pgfmathresult{nan}
  \fi
  }}
  }

\begin{document}
\begin{figure}
  \centering
  \begin{tikzpicture}
  \begin{axis}
  \addplot table[x=x, y=f,
                 discard if not={y}{0},
                 discard if not={z}{0},
                ] {foo.txt};
  \end{axis}
  \end{tikzpicture}
  \caption{$f(x)$ given $y=0$ and $z=0$.}
  \end{figure}
\end{document}

enter image description here

3

Of course. You just need to replace .code by .append code in your definition. The first "resets" the command and applies (only) the new stuff while the later - as the name suggests - appends stuff to the previous one.

% used PGFPlots v1.14
    \begin{filecontents}{foo.txt}
        x y z f
        0 0 0 0
        0 0 1 1
        0 1 0 2
        0 1 1 3
        1 0 0 4
        1 0 1 5
        1 1 0 6
        1 1 1 7
    \end{filecontents}
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
    \pgfplotsset{
        discard if not/.style 2 args={
            % suppress LOG messages about the filtered points
            filter discard warning=false,
            x filter/.append code={
                \edef\tempa{\thisrow{#1}}
                \edef\tempb{#2}
                \ifx\tempa\tempb
                \else
                    \def\pgfmathresult{NaN}
                \fi
            },
        },
    }
\begin{document}
    \begin{tikzpicture}
        \begin{axis}
            \addplot
                table [x=x,y=f] {foo.txt};
            \addplot+ [mark=+]
                table [
                    x=x,y=f,
                    discard if not={y}{0},
                    discard if not={z}{0},
                ] {foo.txt};
        \end{axis}
    \end{tikzpicture}
\end{document}

image showing the result of above code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.