# Using Abs in MeshFunction gives incorrect results

Code:

data = RandomReal[{-3, 3}, 100];
ListLinePlot[data, MeshFunctions -> {Abs[#2] &}, Mesh -> {1}, MeshShading -> {Red, Green}, MeshStyle -> None]


Picture: What's going on? I'm not looking for a workaround, as I'm going to be wanting to use a more complicated mesh function that includes Abs.

• Not exactly the same, but very similar ListLinePlot[data, MeshFunctions -> {(#2) &}, Mesh -> {{1, -1}}, MeshShading -> {Red, Blue}, MeshStyle -> None] Feb 6, 2015 at 20:54
• From the docs: "The Subscript[m, i] should normally be chosen to be continuous monotonic functions", where Subscript[m, i] represent the mesh functions. Abs is not monotonic. Feb 6, 2015 at 23:54

It appears that you are using MeshFunctions -> {Abs[#2] &} to cause the curve to change color when it crosses +1.5 and -1.5, but it does not. This is because, although a line segment of data may cross one of those values, the corresponding line segment of Abs[data] does not necessarily do so. For clarity, consider data modified by two additional points at +3 and -3, with the goal of causing the color to change at exactly +1.5 and -1.5.

data = RandomReal[{-3, 3}, 100]; data = Append[data, 3]; data = Append[data, -3];


The plot in the Question (with PlotRange -> {-3, 3} added for clarity) is

ListLinePlot[data, MeshFunctions -> {Abs[#2] &}, Mesh -> {1},
MeshShading -> {Red, Green}, MeshStyle -> None, PlotRange -> {-3, 3}] The lines near 16, for instance, do not change color. Next, plot Abs of the same data

ListLinePlot[Abs[data], MeshFunctions -> {#2 &}, Mesh -> {1},
MeshShading -> {Red, Green}, MeshStyle -> None, PlotRange -> {-3, 3}] We see that lines of Abs[data] never cross +1.5 at 16 and so do not change color. Hence, they do not change color in the first plot eiher.

To assure the desired color change, the approach suggested by belisarius in his Comment seems preferable.

• Ah, I see, the points that remain green jump from a large positive value to a large negative value! Thanks! Feb 7, 2015 at 1:04
• Yes, and their absolute values change much less. This point was not obvious to me either until I plotted Abs[data]. Thanks for accepting the answer. Feb 7, 2015 at 1:08

I am not sure what your ultimate aim was. I note that Mesh->{1} is not specifying a value of the mesh but number of mesh points. I post this for clarification/facilitation:

data = RandomReal[{-3, 3}, 100];
llp1 = ListLinePlot[data, MeshFunctions -> {Abs[#2] &}, Mesh -> {{1}},
MeshShading -> {Red, Green}, MeshStyle -> None,
Epilog -> {Blue, PointSize[0.02], 