I'm new to R.
I'm trying to draw a square and a line through a point. This is the code I wrote...
plot(c(0, 2), c(0, 2), main="abc", type= "n", xlab = "x", ylab = "y")
rect(0, 0, 1, 1, col=2) #square
m = runif(1, min=0, max=1) #angular coefficient
myLine <- function(x) m*(x-0.5)+0.5 # y = m*(x-0.5)+0.5 --> line through (0.5,0.5)
plot(myLine) #draw myLine
...but it doesn't work. Can you please explain to me what mistakes I made?
Thank you in advance
When you call plot()
, R will usually create a brand new plot; it does not add it the existing plot by default. There are other functions such as points()
, lines()
and curve()
that will draw on the existing plot.
Since you are tying to add a function, then you would need to use curve()
to draw that function myLine
you created. (If instead you wanted to randomly choose an intercept and slope, you could use the abline()
function instead). But using your existing function, the code should look more like this
plot(c(0, 2), c(0, 2), main="abc", type= "n", xlab = "x", ylab = "y")
rect(0, 0, 1, 1, col=2) #square
m <- runif(1, min=0, max=1) #angular coefficient
myLine <- function(x) m*(x-0.5)+0.5 # y = m*(x-0.5)+0.5 --> line through (0.5,0.5)
curve(myLine, add=TRUE) #draw myLine
which gives me this following plot