I want plot the max value in a sine plot. We can use the following code
Plot[Sin[x], {x, 0, 50}, Mesh -> {{.99}},
MeshFunctions -> {#2 &},
MeshStyle -> {PointSize[Large], Red}]
Why can't Mesh -> 1
be used to plot the red point?
But in a mathematics way, I want to use this code
Plot[Sin[x], {x, 0, 50},
Mesh -> {{1}},
MeshFunctions -> {Boole[(Cos[#] == 0) && (-Sin[#] < 0)] &},
MeshStyle -> {PointSize[Large], Red}]
You can see the MeshFunction
doesn't work? Why?
Then I try some other test. For example,I want to emphasize the point above 0.5 to draw on Red. I use this code
Plot[Sin[x], {x, 0, 50},
Mesh -> {{1}},
MeshFunctions -> {Boole[Greater[#2, 0.5]] &}]
It doesn't work again. So I guess the equation PrimePi[z] == 2
will give 2 <= z < 3
. To see whether this region can plot in MeshFunction
, I tried the following:
f[x_, y_] := (x^2 + 3 y^2)*E^(1 - x^2 - y^2)
Plot3D[f[x, y], {x, -2, 2}, {y, -2, 2},
Mesh -> {{1}},
MeshFunctions -> {PrimePi[#3] &}]
You can see the plot is weird.
So what is my problem with MeshFunction
? Can I use MeshFunction
to plot the maximum value in a plot?
Answer
Another alternative is to use ConditionalExpression
using the second-order condition for a local maximum as the second argument:
f = Sin;
Plot[f[x], {x, 0, 20 Pi},
Mesh -> {{0}},
MeshFunctions -> {ConditionalExpression[f'[#], f''[#] < 0] &},
MeshStyle -> {PointSize[Large], Red}]
f = Sin[#] - 1/2 Cos[Pi #] &;
Plot[f[x], {x, 0, 10 Pi},
Mesh -> {{0}},
MeshFunctions -> {ConditionalExpression[f'[#], f''[#] < 0] &},
MeshStyle -> {PointSize[Large], Red}]
You can add additional constraints to the second argument of ConditionalExpression
e.g. f[#]>0
:
Plot[f[x], {x, 0, 20 Pi},
Mesh -> {{0}},
MeshFunctions -> {ConditionalExpression[f'[#],f''[#] < 0 && f[#] > 0] &},
MeshStyle -> {PointSize[Large], Red}]
Update ... or, essentially any constraint:
cond = ((# - 10 Pi)/(2 Pi))^2 + (Pi #2)^2 &;
rplt = RegionPlot[{#, ! #}, {x, 0, 20 Pi}, {y, -2, 2},
PlotLegends -> "Expressions"] &@(4 < cond[x, y] < 16);
meshF = ConditionalExpression[f'[#], f''[#] < 0 && ff@(4 < cond[#, f[#]] < 16)] &;
Row[Table[Plot[f[x], {x, 0, 20 Pi},
Mesh -> {{0}}, ImageSize -> 400,
MeshFunctions -> {meshF},
MeshStyle -> {PointSize[Large], Red},
Epilog -> {Opacity[.6], rplt[[1, 1]]}],
{ff, {Identity, Not}}],
rplt[[2, 1, 1]]]
See also: this great answer by Silvia for a more general method.
Comments
Post a Comment