1

How to avoid plotting lines not defined in a Which function?

fa1[x_] := Which[x >= 15, 1, x >= 10, 0.55, x >= 5, 0.1]
Plot[fa1[x], {x, -1, 20}, BaseStyle -> AbsoluteThickness[4], 
 PlotLegends -> 
  LineLegend["Expressions", BaseStyle -> AbsoluteThickness[4]]]

enter image description here

Mika Ike
  • 3,241
  • 1
  • 23
  • 38

1 Answers1

2

You can post-process the plot to split the line into separate lines.

fa1[x_] := Which[x >= 15, 1, x >= 10, 0.55, x >= 5, 0.1]
plot = Plot[fa1[x], {x, -1, 20},
   BaseStyle -> AbsoluteThickness[4],
   PlotLegends -> LineLegend["Expressions",
     BaseStyle -> AbsoluteThickness[4]]];

linepos = Position[plot, Line];
a = Extract[plot, ReplacePart[First@linepos, -1 -> 1]];
b = Last /@ a;
c = Partition[b, 2, 1];
d = #1 == #2 & @@@ c;
e = DeleteCases[Split[d], {False}];
f = Length /@ e + 1;
g = # + {1, 0} & /@ Partition[Prepend[Accumulate[f], 0], 2, 1];
h = Take[a, #] & /@ g;
plot[[Sequence @@ ReplacePart[First@linepos, -1 -> 1]]] = h;

plot

enter image description here

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
  • Thank you. It´s a solution, but I think that it´s a little complicate for a Mathematica user without huge knowledge of the software. I prefer use easier solutions. – Mika Ike Jul 07 '14 at 10:29
  • @MikaIke - yes, I would use Piecewise in retrospect. Nevertheless, sometimes editing the plot output is expedient. In this particular case there may be a shorter way to subdivide the line; I just took fairly basic steps. – Chris Degnen Jul 07 '14 at 12:14