drawing circle in R

You need to specify asp = 1:

x = runif(100, -1, 1)
y = runif(100, -1, 1)
plot(x, y, asp = 1, xlim = c(-1, 1))
draw.circle(0, 0, 1, nv = 1000, border = NULL, col = NA, lty = 1, lwd = 1)

enter image description here

EDIT: Just a side note, you can make your Monte Carlo function more efficient:

mc.pi = function(n) {

  x = runif(n, -1, 1)
  y = runif(n, -1, 1)
  pin = sum(ifelse(sqrt(x^2 + y^2 <= 1), 1, 0))
  4 * pin/n
}

Fernando's answer is good if you want the circle to actually look like a circle to the user. This answer covers drawing a circle in data dimensions.

If your x and y axes are scaled the same, e.g., if you set your aspect ratio to 1 (asp = 1), then the two methods are equivalent.

# initialize a plot
plot(c(-1, 1), c(-1, 1), type = "n")

# prepare "circle data"
radius = 1
center_x = 0
center_y = 0
theta = seq(0, 2 * pi, length = 200) # angles for drawing points around the circle

# draw the circle
lines(x = radius * cos(theta) + center_x, y = radius * sin(theta) + center_y)

As Gregor pointed out already, you have to distinguish whether or not x and y have the same scale when drawing a circle. In case x and y have the same scale I prefer using symbols for drawing a circle in R. It makes this without specifying vertices and does not need an additional library.

n <- 1000
set.seed(0)
x <- runif(n, -1, 1)
y <- runif(n, -1, 1)

#x and y have the same scale -> Circle
plot(x, y, asp=1)
symbols(x=0, y=0, circles=1, inches=F, add=T)

#In case x and y don't have the same scale -> Ellipse
#Use Gregor's Answer
plot(x,y)
radius <- 1
theta <- seq(0, 2 * pi, length = 200)
lines(x = radius * cos(theta), y = radius * sin(theta))

#Using plotrix
library("plotrix")
plot(x, y, asp=1)
draw.circle(x=0, y=0, radius=1)

plot(x,y)
draw.ellipse(x=0, y=0, a=1, b=1)

Tags:

Plot

R