# Filling two colors when one curve is above or below the other

Let's plot two functions $$2e^{-\pi x^2}$$ and $$e^{-x}$$ and fill the area between two curves with two colors depending on the sign of their difference. However, the following code does not work:

Plot[{2 E^(-Pi x^2), E^(-x)}, {x, 0, 5},PlotLegends -> "Expressions",
Filling -> {1 -> {{2}, {LightBlue, Red}}}, PlotRange -> All]


However, if start the plot with $$-0.01$$, it works!

Plot[{2 E^(-Pi x^2), E^(-x)}, {x, -.01, 5},PlotLegends -> "Expressions",
Filling -> {1 -> {{2}, {LightBlue, Red}}}, PlotRange -> All]


Why is it so weird?

Set MaxRecursion->r and let r<4. Maybe a bug.

r=2;
Plot[{2  E^(-Pi  x^2), E^(-x)}, {x, 0, 5},
PlotLegends -> "Expressions",
Filling -> {1 -> {{2}, {LightBlue, Red}}}, PlotRange -> All,
MaxRecursion -> r]


• Even manually specifying PlotPoints seems to work, for example PlotPoints -> 2 ... Commented Mar 4 at 8:35
• That is a good tip. Does anyone know why it works for points? Commented Jun 6 at 6:47

As a workaround, plotting over the Interval {0,5} works as well as this can be changed.

Clear["Global*"];
f1 = 2 E^(-Pi x^2);
f2 = E^(-x);
c1 = Opacity[0.2, ColorData[97][1]];
c2 = Opacity[0.2, ColorData[97][2]];

Plot[{f1, f2}, x ∈ Interval[{0, 5}]
, PlotRange -> All
, Filling -> {1 -> {{2}, {c2, c1}}}
, PlotLegends -> Placed[LineLegend[Automatic, {f1, f2}], {0.8, 0.6}]
]


Original:

On v12.2.0 running on Win7-x64, there seems to be no issue.

Clear["Global*"];
f1 = 2 E^(-Pi x^2);
f2 = E^(-x);
c1 = Opacity[0.2, ColorData[97][1]];
c2 = Opacity[0.2, ColorData[97][2]];

Plot[{f1, f2}, {x, -1, 3}
, Filling -> {1 -> {{2}, {c2, c1}}}
, PlotLegends -> Placed[LineLegend[Automatic, {f1, f2}], {0.8, 0.6}]
]


Plot[{f1, f2}, {x, 0, 3}
, Filling -> {1 -> {{2}, {c2, c1}}}
, PlotLegends -> Placed[LineLegend[Automatic, {f1, f2}], {0.8, 0.6}]
]


• The problem is that it doesn't work for particular ranges of $x$. Namely, please try with {x, 0, 5}. Commented Mar 4 at 10:14
• I see; I will delete the answer since the choice of domain affects the filling. Thanks @Domen
– Syed
Commented Mar 4 at 10:21
• Domen Can you please check if the workaround works for other versions.
– Syed
Commented Mar 4 at 10:26
• The workaround with Interval works for v13.3 and v14.0 (Cloud). Commented Mar 4 at 10:28