I was hoping to incorporate an If
function into a Plot
option, as in
Plot[Sin[t], {t, 0, 2 Pi}, Filling -> Axis,
FillingStyle -> If[Sin[t] > 0, LightGreen, LightRed]]
or
Plot[Sin[t], {t, 0, 2 Pi}, PlotStyle -> If[Sin[t] > 0, Dashed, Thick]]
to no avail. Is it possible to pass an If
to the plot options?
I know that I can manually accomplish the effect via Piecewise
, but I have more complicated applications in mind where I would not want to manually precompute the interval(s) on which my piecewise defined function would need to be defined.
Answer
Here is yet another crack at this problem.
ConditionalPlot[func_, condition_, varrange_, trueopts_, falseopts_] :=
Module[{plottrue, plotfalse},
plottrue = Plot[If[condition, func], varrange, trueopts];
plotfalse = Plot[If[Not[condition], func], varrange, falseopts];
Show[plottrue, plotfalse, PlotRange -> All]]
The first argument is the function or list of functions you want to plot. The second argument is the condition you want to apply. The third argument is the variable and range to plot in the form {x,xmin,xmax}
. The third and fourth arguments are the options you apply when the condition is true or false, respectively.
For example, the plot you mentioned in your question can be had by
ConditionalPlot[Sin[x],
Sin[x] > 0, {x, 0, 2 Pi}, {Filling -> Axis,
FillingStyle -> LightGreen, PlotStyle -> Dashed}, {Filling -> Axis,
FillingStyle -> LightRed, PlotStyle -> Thick}]
This is versitile, you can give it a compound condition like
ConditionalPlot[Sin[x],
Sin[x] > .7 || Sin[x] < -.7, {x, 0, 2 Pi}, {Filling -> Axis,
FillingStyle -> LightGreen, PlotStyle -> Dashed}, {Filling -> Axis,
FillingStyle -> LightRed, PlotStyle -> Thick}]
You can give it multiple functions to plot
ConditionalPlot[{Sin[x], Cos[x]},
Sin[x] > Cos[x], {x, 0, 4 Pi},
{PlotStyle -> {Red, Thick}, Axes -> False, Frame -> True, BaseStyle -> 14},
{PlotStyle -> {Black, Thick,Dashed}}]
Note that any global options you want to apply to the image in general should go in the trueopts
as it is given to Show
first.
Comments
Post a Comment