[Tex/LaTex] Restrict x domain to several regions

pgfplots

I want to plot a graph and show only the low x-positions and the high x-positions. Right now I use two times \addplot with restrict x domain to achieve this:

\documentclass{standalone}

\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat = newest}  

\begin{document}
\begin{tikzpicture}

\begin{axis}[xmin=-3, xmax=5]

\addplot[restrict x to domain=-3:-1] 
coordinates {
(-3, 8.31160034e-02)
(-2, 2.54685628e-02)
(-1, 7.40715288e-03)
(0, 2.10192154e-03)
(1, 5.87352989e-04)
(2, 1.62269942e-04)
(3, 3.40715288e-03)
(4, 7.40715288e-03)
(5, 2.40715288e-02)
};

\addplot[restrict x to domain=1:5] 
coordinates {
(-3, 8.31160034e-02)
(-2, 2.54685628e-02)
(-1, 7.40715288e-03)
(0, 2.10192154e-03)
(1, 5.87352989e-04)
(2, 1.62269942e-04)
(3, 3.40715288e-03)
(4, 7.40715288e-03)
(5, 2.40715288e-02)
}; 

\end{axis}    

\end{tikzpicture}
\end{document}

enter image description here

I wonder if the trick can also be done with just one \addplot?

Best Answer

You can use

restrict expr to domain={<expr>}{min:max}

with in this case <expr> any appropriate function of x. In your particular example, using {x*x}{1:+inf} would work because of the particular choice of ranges which happen to have +/-1 as their end-points. In general one could use

restrict expr to domain={(x>=a1)*(x<=b1)+(x>=a2)*(x<=b2)}{1:+inf}

to restrict to x to lie in one of the two intervals a1:b1 and a2:b2, since (x>=a) returns 1 when true and 0 otherwise. This type of expression is also better from the point of view of overflow in calculations. Alternatively you can use && for "and" and || for "or" operations:

restrict expr to domain={(x>=-3)&&(x<=-1)||(x>=1)&&(x<=5)}{1:1}

noting that && has higher precedence.

Sample output

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat = newest}  

\begin{document}

\begin{tikzpicture}
\begin{axis}[xmin=-3, xmax=5]
\addplot[restrict expr to domain={x*x}{1:+inf}] 
coordinates {
(-3, 8.31160034e-02)
(-2, 2.54685628e-02)
(-1, 7.40715288e-03)
(0, 2.10192154e-03)
(1, 5.87352989e-04)
(2, 1.62269942e-04)
(3, 3.40715288e-03)
(4, 7.40715288e-03)
(5, 2.40715288e-02)
};
\end{axis}    
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[xmin=-3, xmax=5]
\addplot[restrict expr to domain={(x>=-3)*(x<=-1)+(x>=1)*(x<=5)}{1:+inf}] 
coordinates {
(-3, 8.31160034e-02)
(-2, 2.54685628e-02)
(-1, 7.40715288e-03)
(0, 2.10192154e-03)
(1, 5.87352989e-04)
(2, 1.62269942e-04)
(3, 3.40715288e-03)
(4, 7.40715288e-03)
(5, 2.40715288e-02)
};
\end{axis}    
\end{tikzpicture}

\end{document}