# Plot discontinuous function with black and white disks marking discontinuities

Let's say I'd like to plot Sign[x + 0.5]:

Plot[Sign[x + 0.5], {x, -1, 1}]

Mathematica will give this:

This plot does not show very clearly the value of Sign[x + 0.5] at x = -0.5: is it 1? is it -1? No, it's 0, but there is no indication of which it is on the plot. This is what I'd like to achieve:

(I used Paint to add the markers.) How can I make it Mathematica do it?

-
Related this and this –  Vitaliy Kaurov Dec 27 '13 at 0:01

Update: PlotPiecewise now automatically tries to convert a non-Piecewise function into one using PiecewiseExpand. PiecewiseExpand will also do some simplification, such as factoring and reducing a rational function; to avoid that, pass a Piecewise function directly. PlotPiecewise will not alter the formulas in a Piecewise. Note, however, that Mathematica automatically reduces x (x - 1) / (x (x - 2)) but not (x^2 - x) / (x (x - 2)).

A while back I wrote a function PlotPiecewise to produce standard pre-calculus/calculus graphs of Piecewise functions. It works a lot like plot. It evolved from time to time, but it's nowhere near a complete package. For instance, PlotPiecewise is not HoldAll like Plot, because it was convenient for a certain use-case and my typical uses didn't need it either. There are a few options, but not really a complete set. Another limitation is that it was intended for rather simple piecewise functions, of the type one might ask students to graph by hand. For instance, it uses Reduce and Limit to find asymptotes but doesn't check if they worked; one should really check. It won't handle functions that are too complicated or that cannot be expanded as Piecewise functions.

I'll offer it, since it seems to do what the OP asks and I've already written. It seems worth sharing. I hope the community appreciates it. Code dump at the end.

OP's example

Update: There is no longer a need to expand Sign. PlotPiecewise will automatically do it.*

PlotPiecewise[Sign[x + 1/2], {x, -1, 1}]

More Examples

PlotPiecewise[
Piecewise[{
{ 1 / (-1 + 2 x),      0 < x <= 1},
{ 2,                       x == 0},
{ -x,                      x < 0},
{ (2 - x) / (-3 + x),  1 < x < 4},
{ -6 + x,              4 < x}},
Indeterminate],
{x, -2, 6.5},
AspectRatio -> Automatic, PlotRange -> {-2.8, 3.1},
Ticks -> {Range[-3, 6], Range[-4, 3]}]

g[t_] := Piecewise[{
{Abs[1 + t], -2 <= t < 0},
{2, t == 0},
{2 - Cos[Pi*t], 0 < t < 2},
{(-16 - 12*t + t^3)/(8*(-4 + t)), t >= 2}},
Indeterminate];
PlotPiecewise[g[t], {t, -2, 6}, PlotRange -> {-2, 9}, DotSize -> Offset[{3, 3}]]

Update: New cases handled

The updated code can do these things:

PlotPiecewise[Exp[(Sign[Sin[x^2]] - 3/4) x/2] - 1, {x, 0, 10}]

PlotPiecewise[
Piecewise[{
{(-1 + 3*x)^(-1), -1 < x <= 1},
{Tan[Pi*x], 1 < x < 11/2}},
Indeterminate],
{x, -2, 6.5}, AspectRatio -> Automatic, PlotRange -> {-2.8, 3.1},
Ticks -> {Range[-3, 6], Range[-4, 3]}]

Code dump

Here is an update. It is I hope written in a somewhat better style. I also took the opportunity to add a couple of features. PlotPiecewise will automatically apply Piecewise expand, and if it produces a Piecewise function it will plot it. It will also handle a wider range of conditions in a Piecewise function. There is a bit more error checking, and some error messages have been added. It is still not HoldAll. Since Mr.Wizard prodded me to improve the code, I tried to keep it so that it would work in V7.

Clear[
PlotPiecewise,           (* user interface *)
PlotPiecewiseplot,      (* generates the plot of a Piecewise function *)
PlotPiecewiseDot,        (* handles the end points of subdomains --
Sows empty/filled dots and asymptotes *)
InteriorPoints,          (* handles discontinuities in the interior of a subdomain *)
PlotPiecewisesolve,     (* Reduce + postprocessing, to handle more general
Piecewise conditions *)
PlotPiecewiseexpand];   (* Used by PlotPiecewisesolve to expand generated
parameter C[1] *)

PlotPiecewise::usage =
"PlotPiecewise[Piecewise[...], {x, a, b}, opts]";
PlotPiecewise::limindet =
"Limit  is not numeric or infinite at ";
PlotPiecewise::nonpw =
"Function  is not a Piecewise function or did not expand to one";

Options[PlotPiecewise] =
Join[{"DotSize" -> Automatic, "EmptyDotStyle" -> Automatic,
"FilledDotStyle" -> Automatic, "AsymptoteStyle" -> Automatic,
"BaseDotSize" -> Offset[{2, 2}]}, Options[Plot]];
Options[EmptyDot] = Options[FilledDot] = Options[Asymptote] =
Options[PlotPiecewiseplot] = Options[PlotPiecewise];

(* graphics elements *)
EmptyDot[pt_, opts : OptionsPattern[]] := {White,
OptionValue["EmptyDotStyle"] /. Automatic -> {},
Disk[pt,
OptionValue["DotSize"] /.
Automatic -> OptionValue["BaseDotSize"]]};
FilledDot[pt_,
opts : OptionsPattern[]] := {OptionValue["FilledDotStyle"] /. Automatic -> {},
Disk[pt,
OptionValue["DotSize"] /. Automatic -> OptionValue["BaseDotSize"]]};
Asymptote[x0_, opts : OptionsPattern[]] := {Dashing[Large],
OptionValue["AsymptoteStyle"] /. Automatic -> {},

(* PlotPieceDot - Sows piecewise breaks, tagged with three ids;
"filled"    -> {x,y};
"empty"     -> {x,y};
"asymptote" ->  x;
An entry in a Piecewise function has the form: piece = {formula, condition}
*)

(* some constants *)
$filledRelations = Equal | LessEqual | GreaterEqual;$emptyRelations = Greater | Less;
$inequality = Greater | Less | LessEqual | GreaterEqual; (* auxiliary function: causes Conditional solutions to expand to all possibilities; (arises from trig eq, and C[1] -- perhaps C[2], etc? *) PlotPiecewiseexpand[cond_Or, var_] := PlotPiecewiseexpand[#, var] & /@ cond; PlotPiecewiseexpand[cond_, var_] := Reduce[cond, var, Backsubstitution -> True]; PlotPiecewisesolve[eq_, var_] := {var -> (var /. #)} & /@ List @ ToRules @ PlotPiecewiseexpand[ Reduce[eq, var, Reals, Backsubstitution -> True], var] /. {False -> {}}; (* PlotPiecewiseDot -- Calls auxiliary function InteriorPoints Breaks down compound inequalities into simple inequalities From simple inequalities, determines dots/asymptotes From equalities, sows a dot, if formula is defined *) PlotPiecewiseDot[piece_] := (InteriorPoints[piece]; PlotPiecewiseDot[piece, "sow"]); PlotPiecewiseDot[{formula_, HoldPattern @ Inequality[a_, rel1_, b_, rel2_, c_]}, "sow"] := PlotPiecewiseDot[#, "sow"] & /@ {{formula, rel1[a, b]}, {formula, rel2[b, c]}}; PlotPiecewiseDot[{formula_, (rel :$inequality)[a_, b_, c_]}, "sow"] :=
PlotPiecewiseDot[#, "sow"] & /@ {{formula, rel[a, b]}, {formula, rel[b, c]}};

PlotPiecewiseDot[{formula_, cond_Equal}, "sow"] :=
With[{a = PlotPiecewisevar /. #, yy = formula /. #},
If[NumericQ[Abs[yy]],
Sow[{a, yy}, "filled"]]] & /@
PlotPiecewisesolve[
cond && LessEqual @@ PlotPiecewisedomain[[{2, 1, 3}]],
PlotPiecewisevar] (* check =? *);
PlotPiecewiseDot[{formula_, cond : (rel : $inequality)[_, _]}, "sow"] := With[{a = PlotPiecewisevar /. #, yy = Limit[formula, First @ #, Direction -> If[MatchQ[rel, Greater | GreaterEqual], 1, -1]]}, If[Abs[yy] == Infinity, Sow[a, "asymptotes"], If[NumericQ[yy], Sow[{a, yy}, If[MatchQ[rel,$filledRelations], "filled", "empty"]],
Message[PlotPiecewise::limindet, yy, a]]
]] & /@
PlotPiecewisesolve[
Equal @@ cond && LessEqual @@ PlotPiecewisedomain[[{2, 1, 3}]],
PlotPiecewisevar] (* check =? *);
(*
auxiliary function: finds discontinuities inside intervals
*)
InteriorPoints[{formula_, cond_}] :=
With[{solns =
PlotPiecewisesolve[
Denominator[formula, Trig -> True] == 0 &&
(cond /. {LessEqual -> Less, GreaterEqual -> Greater}) &&
LessEqual @@ PlotPiecewisedomain[[{2, 1, 3}]],
PlotPiecewisevar]},
With[{a = PlotPiecewisevar /. #, yy = Limit[formula, First@#]},
If[Abs[yy] == Infinity,
Sow[a, "asymptotes"],
If[NumericQ[yy], Sow[{a, yy}, "empty"],
Message[PlotPiecewise::limindet, yy, a]]
]] & /@ solns
];

(* The main plotting function *)
PlotPiecewiseplot[f : HoldPattern @ Piecewise[pieces_, default_],
domain : {var_, a_, b_},
opts : OptionsPattern[]] /; (PlotPiecewisevar = var;
PlotPiecewisedomain = SetPrecision[domain, Infinity];
True) :=
With[{exceptions = Last @ Reap[
PlotPiecewiseDot[#(*,opts*)] & /@
If[default =!= Indeterminate,
Append[pieces, (* add True (default) case to pieces *)
{default, Reduce[Not[Or @@ (Last /@ pieces)]]}],
pieces],
{"asymptotes", "empty", "filled"}],
plotopts = FilterRules[{opts}, Cases[Options[Plot], Except[Exclusions -> _]]]},
With[{exclusions = Join[
If[OptionValue[Exclusions] === None,
{},
Flatten[{OptionValue[Exclusions]}]],
PlotPiecewisevar == # & /@ Flatten[First @ exceptions]]},
With[{curves = Plot[f, domain, Evaluate @ Join[{Exclusions -> exclusions}, plotopts]]},
Show[curves,
Graphics[{ColorData[1][1], EdgeForm[ColorData[1][1]],
OptionValue[PlotStyle] /. Automatic -> {},
Map,
{{ Asymptote[#, PlotRange -> PlotRange[curves], opts] &,
EmptyDot[#, opts] &,
FilledDot[#, opts] & },
If[Depth[#] > 2, First[#], #] & /@ exceptions}]}]]]]
]

(* The user-interfaces *)

PlotPiecewise[f : HoldPattern@Piecewise[pieces_, default_], domain_,
opts : OptionsPattern[]] := PlotPiecewiseplot[f, domain, opts];

(* tries to expand f as a Piecewise function *)
PlotPiecewise[f_, domain : {var_, a_, b_}, opts : OptionsPattern[]] /;
With[{pwf = Assuming[var \[Element] Reals, PiecewiseExpand[f]]},
PlotPiecewisegraphics = PlotPiecewiseplot[pwf, domain, opts];
True,
Message[PlotPiecewise::nonpw, f];
False]] := PlotPiecewisegraphics
-
quite a nice answer! –  chris Dec 27 '13 at 10:28
It looks like this code could benefit from refactoring. Would you care to work with me on that? –  Mr.Wizard Dec 27 '13 at 13:25
This is impressive. I'm baffled by the lack of ability to make common plots in Mathematica. :/ –  user11426 Dec 27 '13 at 19:44
@Mr.Wizard I went ahead and made some changes. If you have something to suggest, I would welcome it. Thanks! –  Michael E2 Dec 30 '13 at 6:14
I've been quite busy. I see that you replaced the many Part operations, which were the primary things I wanted to change. I'm sorry I missed an opportunity to work with you on this. –  Mr.Wizard Dec 30 '13 at 14:04
show 1 more comment

## Update:

To overcome the issue I mention in the comment, also to make it more general, here is an upgraded version, which can deal with clipping and pointwise exclusion, and preserve styles specified in the original plot.

The main function is this discontinuousHighlighter:

Clear[discontinuousHighlighter]
discontinuousHighlighter[origplot_, {excluMarker_, clipMarker_}, radius_: 3] :=
Module[{clipIntvX, black = Black, white, edgestyle},
edgestyle = {AbsoluteThickness[1], black};
white = If[# === None, White, #] &[Background /. AbsoluteOptions[origplot, Background]];
(* clipped intervals: *)
clipIntvX = Interval @@ Join @@ Cases[origplot,
{style___,lines:Longest[Line[_]..],___}/;Not[FreeQ[{style}, clipMarker]]:>{lines}[[All,1,All,1]],
∞];
origplot /.
(* exclusion boundary markers on curve: *)
{style___, Point[pts__]} /; Not[FreeQ[{style}, excluMarker]] :>
(black = If[# === {}, black, #[[-1]]] &@
DeleteCases[Cases[{style}, (RGBColor | Hue)[__], ∞], excluMarker];
edgestyle = Join[edgestyle, {style /. Directive | EdgeForm -> Sequence} // Flatten];
Flatten[{
EdgeForm[edgestyle],
FaceForm[white],
Module[{pt = #},
If[IntervalMemberQ[clipIntvX, pt[[1]]],
{},
]
] & /@ pts} /. excluMarker -> Sequence[]]
) /.
(* exclusion markers on x axis: *)
{style___, lines : (Line[_] ..)} /; FreeQ[{style}, clipMarker] && Not[FreeQ[{style}, excluMarker]] :>
Join[
{style, lines} /. excluMarker -> Sequence[],
Flatten[{
EdgeForm[edgestyle],
FaceForm[black],
Disk[{Mean[#[[All, 1]]], 0}, Offset[radius]] & @@@ {lines}
}] /. excluMarker -> black
] /.
(* clipped interval: *)
{style___,lines:Longest[Line[_]..],post___}/;Not[FreeQ[{style},clipMarker]]&&Not[FreeQ[{post},clipMarker]] :>
({style, lines} /. clipMarker -> Sequence[]) //
Show[#, PlotRangeClipping -> False, PlotRangePadding -> Scaled[.05]] &
]

Basically, we calculate the x coordinates of the filled disks from the exclusion lines, and convert the endpoints on curve to hollow disks.

To use the function, wrap Plot[...] with it:

Module[{excluMarker = RGBColor @@ RandomReal[1, 3], clipMarker = RGBColor @@ RandomReal[1, 3]},
discontinuousHighlighter[
Plot[Exp[(Ceiling[Sin[x^2]] - 9/10) x] - 1.01, {x, -10, 10},
PlotStyle -> Directive[AbsoluteThickness[3]],
PlotPoints -> 1000, MaxRecursion -> 15,
PlotRange -> {-1, 1},
ExclusionsStyle -> {
Directive[GrayLevel[.8], Dashed, excluMarker],
Directive[EdgeForm[{Lighter[Purple]}], excluMarker]
},
ClippingStyle -> Directive[Darker[Green], Thin, clipMarker],
Background -> Lighter[Yellow, .9]
],
{excluMarker, clipMarker},
3 ]
]

You can use any style in ExclusionsStyle and ClippingStyle. As long as they contain excluMarker and clipMarker, the result should be parsed correctly by discontinuousHighlighter. And hollow disks will automatically fit the background color.

If you want to draw those disks and circles automatically, a convenient way would be post-processing a styled plot.

First we generate a unique mark for the ExclusionsStyle and ClippingStyle:

excluColor = RGBColor @@ RandomReal[1, 3];
clipColor = RGBColor @@ RandomReal[1, 3]

Use them to style the exclusions:

origplot = Plot[Floor[Tan[x]], {x, 0, π},
PlotStyle -> Directive[Thick],
Exclusions -> {Automatic, Cos[x] == 0},
ExclusionsStyle -> {excluColor, excluColor}]

and the clipped intervals (we need this because the ExclusionsStyle seems to have a higher priority than ClippingStyle, and we don't want to mistake the clipped intervals for the discontinuous intervals):

clipplot = Plot[Floor[Tan[x]], {x, 0, π},
Exclusions -> {Automatic, Cos[x] == 0},
ExclusionsStyle -> None,
ClippingStyle -> clipColor]

clipIntv = Interval @@ Cases[clipplot,
{___, clipColor, lines : (Line[_] ..)} :>
Through[{Min, Max}@Flatten[#[[All, 1]] & @@@ {lines}]],
∞];

To draw the circles correctly, we need to know the aspect-ratio and set a appropriate radius:

{rgx, rgy} = PlotRange.{-1, 1} /. AbsoluteOptions[origplot, PlotRange];
asprat = AspectRatio /. AbsoluteOptions[origplot, AspectRatio];

The remaining work is some replacements:

origplot /.
{excluColor, lines : (Line[_] ..)} :>
Flatten[{Black, Module[{x = Mean[#[[All, 1]]]},
If[IntervalMemberQ[clipIntv, x],
{},
Disk[{x, 0}, radius {1, 1/asprat rgy/rgx}]
]
] & @@@ {lines}}] /.
{excluColor, Point[pts__]} :>
Flatten[{EdgeForm[Black], FaceForm[White], Module[{pt = #},
If[IntervalMemberQ[clipIntv, pt[[1]]],
{},
]
] & /@ pts}] //
Show[#, PlotRangeClipping -> False, PlotRangePadding -> Scaled[.05]] &

-
Nice! For discrete plots, one can also use DiscretePlot with ExtentMarkers –  rm -rf Dec 27 '13 at 1:27
@rm-rf Thanks. There are still issues here. e.g. for Plot[Exp[(Ceiling[Sin[x^2]]-9/10)x]-1,{x,0,10},PlotRange->{All,1}], some boundary points doesn't get circled. I'll try to fix it after lunch :) –  Silvia Dec 27 '13 at 1:38
Look up Offset[{dx, dy}, the last entry under Details. –  Michael E2 Dec 27 '13 at 3:53
@MichaelE2 Thanks, didn't know that! Will use it the next update. –  Silvia Dec 27 '13 at 4:51
@MichaelE2 I tried the Tooltip way, but they sometimes change to something like Tooltip[{}, "exclusion", TooltipStyle -> "TextStyling"], so I kept my RGBColor method. But Offset[radius] is really a great function. Thanks for the information! –  Silvia Dec 27 '13 at 16:44

If you know a priori where are the discontinuities:

p = Plot[Sign[x + 0.5], {x, -1, 1}];
ap = AspectRatio /. AbsoluteOptions[p, AspectRatio]
epilog = {FaceForm[White], EdgeForm[Black],
Disk[{-1/2, -1}, .03 { ap, 1 }], Disk[{-1/2, 1}, .03 { ap, 1 }],
FaceForm[Black], Disk[{-1/2, 0}, .03 {ap, 1}]};

Plot[Sign[x + 0.5], {x, -1, 1}, Epilog -> epilog]

-
Thanks. This is great, but sadly, I may not know where discontinuities are. It would be great to generalise that; for more complicated functions it will be quite a hassle to specify these points. :( –  user11426 Dec 26 '13 at 17:01
On a related note, Wolfram|Alpha is able to create something very similar to what I'd like to: wolframalpha.com/input/?i=discontinuities+of+sign%28x%2B0.5%29 (Meaning Mathematica should be able too.) –  user11426 Dec 26 '13 at 17:06
@user11426 Plot[Sign[x + 0.5], {x, -1, 1}, ExclusionsStyle -> {Dashed, PointSize[Large]}] –  Rojo Dec 26 '13 at 17:53
I hope it is possible and simple to do this automatically for those discontinuities that Exclusions already detects –  Rojo Dec 26 '13 at 17:54
Yay! This is near perfect! But lacks white points. :( –  user11426 Dec 26 '13 at 18:10