2

I want to draw a circle like this.

The equation of the circle is : (x-4)^2+(y-2)^2=25

So i wrote down R codes using curve command. But it is not drawing circle exactly.

 curve(4-sqrt(25-(x-2)^2),xlim=c(-4,10),ylim=c(-4,10))

 curve(4+sqrt(25-(x-2)^2),add=TRUE,col="red")

and it is producing circle like following :enter image description here.

Where is/are the fault(s) in my commands? also the commands produce warning

 Warning message:
 In sqrt(25 - (x - 2)^2) : NaNs produced

I know there is a function draw.circle in R.

But i want to identify my codes fault(s).

2
  • there are far better, and simpler, ways to draw a circle centered at a specified origin and known radius. Look around a bit. Commented Jan 3, 2015 at 14:31
  • 1
    @CarlWitthoft: OP implies that they are doing this for pedagogical reasons. Commented Jan 3, 2015 at 14:35

1 Answer 1

4

The warning message comes from the fact that you try to take sqrt() of a negative number. The circle can be drawn by increasing the data-points.:

N<-10000
curve(4-sqrt(25-(x-2)^2),xlim=c(-4,10),ylim=c(-4,10),n=N)
curve(4+sqrt(25-(x-2)^2),add=TRUE,col="red",n=N)

of course you should in general use the arguments of from,to to control the calculations of the data-points pointed out by Ben:

curve(4-sqrt(25-(x-2)^2),xlim=c(-4,10),ylim=c(-4,10),from=-3,to=7,n=N)
curve(4+sqrt(25-(x-2)^2),add=TRUE,col="red",from=-3,to=7,n=N) 

also notice you are plotting (y,x) and not the usual (x,y). Judging by the comments, it seems you want:

curve(2-sqrt(25-(x-4)^2),xlim=c(-4,10),ylim=c(-4,10),from=-1,to=9,n=N)
curve(2+sqrt(25-(x-4)^2),add=TRUE,col="red",from=-1,to=9,n=N)
Sign up to request clarification or add additional context in comments.

8 Comments

It is also producing warning and i didn't understood the reason why didn't xlim and ylim cover it ? Why did i need to add n and if i would use from= , to= argument inside curve instead of xlim and ylim , could i able to draw the circle parfectly ?
xlim and ylim are arguments to plot, from and to is used by curve to calculate the datapoints, eg. ensure you are not trying to take sqrt() of a negative number in this case. I just increased the number of points because it was a quick fix.
But (4,7) should be a point on circumference. But it is not so. I've justified it by abline(h=7,v=4)
I might just delete my answer since your answer covers it. I think that once you specify from and to, however, you really don't need to increase N -- the default 101 points should be just fine. 10000 is overkill.
yes xlim= will then narrow it down to almost c(from=,to=) and ylim= given by c( min(f(x)), max(f(x)) ) where f() is the function given as argument to curve.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.