Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square function drawing in r plot

Tags:

r

I would like to draw a square function in a r plot like this plot (black line) from here:

enter image description here

How can I do this one in R?

like image 564
Kaja Avatar asked Sep 18 '25 00:09

Kaja


2 Answers

You can use a definition of the square wave - use the sign function on a periodic function:

plot(function(x) sign(sin(x)),-10,10,n=1000)

square wave

like image 139
James Avatar answered Sep 20 '25 14:09

James


You can use lines to draw any arbitrary pattern by specifying vectors of x and y coordinates.

plot(NA, xlim=c(0,10), ylim=c(-2,2))
lines(rep(0:11,each=2),rep(c(-1,1,1,-1),6))

That's helpful if you have multiple things you want to plot. But, you can also obtain the same result directly in plot.default using the type='s' argument:

plot(rep(0:11,each=2),rep(c(-1,1,1,-1),6), xlim=c(0,10), ylim=c(-2,2), type='s')

enter image description here

like image 29
Thomas Avatar answered Sep 20 '25 16:09

Thomas