# How to plot $x^2$ over $-5<x<-1\cup1<x<5$

Is it possible to plot a function over a interval with a gap in the middle; e.g., $f(x)=x^2$ over $-5<x<-1\cup1<x<5$?

I am using Mathematica 7 and most of the options in the answers don't seem to work for me.

In V8 and up, one can use ConditionalExpression:

Plot[ConditionalExpression[x^2, -5 < x < -1 || 1 < x < 5], {x, -5, 5}]


Response to updated question

This might work in all versions of Mathematica:

Show[
Plot[x^2, {x, -5, -1}],
Plot[x^2, {x, 1, 5}],
PlotRange -> All]

• Piecewise[] with Indeterminate as the default case works here as well. – J. M.'s ennui Dec 9 '16 at 21:11
• @J.M. Nice to hear from you, again! – Michael E2 Dec 9 '16 at 22:45
• It's nice to be around again, for sure. :) I was ill for most of my hiatus... – J. M.'s ennui Dec 9 '16 at 22:48
• @J.M. I'm sorry to hear that. I wish you better health in the coming year! – Michael E2 Dec 9 '16 at 22:49

You can also define f conditionally:

f[x_] := x^2 /; (-5 < x < -1 || 1 < x < 5)

• This is good, but f[x_ /; (-5 < x < -1 || 1 < x < 5)] := x^2 is better – m_goldberg Nov 20 '16 at 22:22

With

reg = ImplicitRegion[-5 < x < -1 || 1 < x < 5, x]


or

reg = Interval[{-5, -1}, {1, 5}]


do

Plot[x^2, {x} ∈ reg]


EDIT

This might work for v7:

Plot[If[-5 < x < -1 || 1 < x < 5, x^2], {x, -5, 5}]

• I am using Mathematica 7 and these options don't seem to work. – gbd Nov 20 '16 at 22:17
• This is a nice V10+ solution to the problem: +50 just to draw attention to it for future users with an up-to-date Mathematica. Plot[x^2, {x} ∈ Interval[{-5, -1}, {1, 5}]] seems particularly nice to code. – Michael E2 Nov 20 '16 at 22:48
• @MichaelE2 Thanks for the kind words :) – corey979 Nov 20 '16 at 23:03
• Hmm, when I started the bounty, the least award on the popup menu was 100. Well, I've seen +50 bounties, so I probably messed up somehow. But what the heck, think of it as a holiday bonus. Don't spend it all in one place. :) -- As I said, I like the fact that one just specifies the desired domain, and you don't have to define a new, temporary, auxiliary function or other such nonsense. – Michael E2 Nov 26 '16 at 19:28

Another way is with the option RegionFunction:

Plot[x^2, {x, -5, 5}, RegionFunction -> Function[x, -5 < x < -1 || 1 < x < 5]]


• I guess this should work in V6 and higher. – Michael E2 Nov 21 '16 at 2:20