# How to plot correctly a discontinuous function?

If you want to plot a discontinuous functions, by example with this

``````using Plots
r = -5:.1:5
plot(r, floor.(r))
``````

you get a graph with a continuous line, however the function have a discontinuity at any integer. How to prevent that the graph would be a continuous line, that it plot correctly jumps at each discontinuity point?

`Plots` doesnâ€™t know whether or not your function is continuous. You know that, but `plot` just gets a bunch of points that could have come from anywhere. I think you have two options:

• plot the function piecewise yourself (relying on your knowledge where the jumps will be) or
• prevent the problem altogether and use `scatter`.

But maybe there exists some plot knowledge that Iâ€™m not aware of to make this happen more easily.

Injecting NaNs where you want the plot to be discontinuous appears to work, for example (in a very inelegant fashion):

``````using Plots
r = -5:.1:5
r1 = [r[1]]
for k = 2:length(r)
if floor(r[k-1])!=floor(r[k])
push!(r1,NaN)
end
push!(r1,r[k])
end
plot(r, floor.(r))
plot!(r1, floor.(r1))
``````

You could also add â€śextrapolated pointsâ€ť to the subinterval before each discontinuity to â€śfill the full plot intervalâ€ť, but that of course requires choosing how to extrapolate the continuous data before the discontinuity.

4 Likes