[R] Plot step function

Duncan Murdoch murdoch.duncan at gmail.com
Sat Feb 6 17:05:56 CET 2016


On 06/02/2016 7:11 AM, jupiter wrote:
> Hi,
>
> I am just starting to learn R, sorry for asking a simple question. How can
> plot a line x <= 0 y = 0, x > 0 y = 1?
>

There are lots of ways.  One is

curve(ifelse(x < 0, 0, 1), from=-2, to=2)

This isn't perfectly vertical at x=0; a more accurate approach would be 
to work out the coordinates of the endpoints and two corners in the 
appropriate order, and join them by lines.  For example,

plot(c(-2,0,0,2), c(0,0,1,1), type="l")

In either case you'll probably want to change axis labels using xlab or 
ylab arguments.

Duncan Murdoch



More information about the R-help mailing list