Plot step function [x+1/2]

Hi all,

I have been trying to plot [x+1/2] learning from the codes at my old thread:

But it returns not the plot that I want. I change 1 into 1.5 it still not working. Maybe it takes more than just that.

So you want the plot from your old post, but shifted 0.5 to the left? or am I interpreting that correctly?

You probably need to make sure you have the x-grid at correct locations to be able to draw that (i.e. at x.5 instead of x.0).

yes shifted 0.5 to the left, that is correct, because basically it is still using the rules of step function.

Yeah, but have you changed your x values so they are actually hitting the half steps instead of the integers? So x=-5.5:1:3.5 or something like that?

I use this:

using Plots; gr()

f(x) = floor(x)
x = -5.5:1:4.5
y = f.(x)
plot(x[1:2], [y[1], y[1]], label=L"f(x) = \lfloor x \rfloor", legend=:topleft,legend_foreground_color=:white, legend_font_color=:blue3, color=:blue3, showaxis=false, tickfontcolor=:white)
# axis and 
hline!((0,0), color=:black, label="")
vline!((0,0), color=:black, label="")
for i in x
    if i!= 0
        annotate!(i,-0.2, (i, 7))
    end
end
for i in y
    if i != 0
        annotate!(-.2, i, (i, 7))
    end
end

for i in 2:length(x)-1
    plot!(x[i:i+1], [y[i], y[i]], label="", color=:blue3, lw=2)
    scatter!(x[i], y[i], marker=:circle, markersize=8, label="")
end


got error:
LoadError: Cannot convert Float64 to series data for plotting
Stacktrace:

Seems like it is unhappy about getting floats, so maybe the line with scatter! could be changed to something like scatter!(x[i:i], y[i:i], ....) which would make them one element arrays. Does this work?

1 Like

It does not show error but shows no plot as well.

Yes scatter needs arrays, so the usual way to write this would be scatter([x], [y]).

For a plot to be shown it has to be the return value of the last evaluated expression. As loops in Julia return nothing, you need to either explicitly create a plot object and call it like this

p = plot()

for x ∈ 2:length(x)-1
    plot!(...)
    scatter!(...)
end
 
p

or add a call to current() to your code, which will just display the last plot object you’ve plotted to.

1 Like

This works finally, after few days / week

using Plots; gr()

f(x) = floor(x + 1/2)
x = -5.5:1:4.5
y = f.(x)
plot(x[1:2], [y[1], y[1]], label=L"f(x) = \lfloor x + 1/2 \rfloor", legend=:bottomleft,legend_foreground_color=:white, legend_font_color=:blue, color=:blue, showaxis=false, tickfontcolor=:white)
# axis and 
hline!((0,0), color=:black, label="")
vline!((0,0), color=:black, label="")
for i in x
	if i!= 0
		annotate!(i,-0.2, (i, 7))
	end
end
for i in y
	if i != 0
		annotate!(-.2, i, (i, 7))
	end
end
annotate!(-.2, -.2, ("0", 7))
for i in 2:length(x)-1
	plot!(x[i:i+1], [y[i], y[i]], label="", color=:blue, lw=2)	
end
scatter!(x[1:end-1], y[1:end-1], markersize=3, markercolor=:blue, label="")
scatter!(x[2:end], y[1:end-1], markersize=3, markercolor=:white, label="")