在 R 中绘制圆圈 [英] drawing circle in R

查看:94
本文介绍了在 R 中绘制圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么下面的代码没有给我完整的圆圈而只给出了它的一部分.此外,我不知道如何在以 (0,0) 为中心且 r=1 和 a=2 的正方形内显示圆上或圆外的点.

I don't know why the following code doesn't give me the complete circle and gives only parts of it. Also I don't know how I can show my points on the circle or outside of it within a square both centered at (0,0) with r=1 and a=2.

library("plotrix")
n<-1000
plot.new()
frame()
x<-runif(n,-1,1)
y<-runif(n,-1,1)
for (i in 1:n) { plot(x[i],y[i])}
draw.circle(0,0,1,nv=1000,border=NULL,col=NA,lty=1,lwd=1)

这是输出

所以我将其固定为以下内容,当我有 100 点时,图表如下所示.为什么不显示完整的圆圈?

So I fixed it to the following and when I have 100 points the graph looks the following. Why the complete circle isn't shown?

plot(x,y)
draw.circle(0,0,1,nv=1000,border=NULL,col=NA,lty=1,lwd=1)

所以多亏了费尔南多,我修正了情节,现在它看起来像这样,但我希望 x 的范围从(-1 到 1),就像 y 一样.xlim 没有用.你知道怎么回事吗?

So thanks to Fernando I fixed the plot and now it looks like this but I want it to have range from (-1 to 1) for x like it is for y. xlim didn't work. Do you know what's wrong?

magnitude = function(x, y) {
  stopifnot(isTRUE(all.equal(length(x),length(y))))
  return (sqrt(x^2 + y^2))
}
library("plotrix")
monte.carlo.pi<-function(n,draw=FALSE)
{
  circle.points<-0
  square.points<-0
  x<-runif(n,-1,1)
  y<-runif(n,-1,1)
  for (i in 1:n)
  {
    #if ((x[i])^2 + (y[i])^2 <=1)
    if (magnitude(x[i],y[i])<=1)
    {
      circle.points<-circle.points+1
      square.points<-square.points+1
    } else
    {
      square.points<-square.points+1
    }
  }
  if (draw==TRUE)
  {
    plot.new()
    frame()
    plot(x,y,asp=1,xlim=c(-1,1),ylim=c(-1,1))
    draw.circle(0,0,1,nv=1000,border=NULL,col=NA,lty=1,lwd=1)
    rect(-1,-1,1,1)
    return(4*circle.points / square.points)
  }
}

并调用如下函数:

monte.carlo.pi(100,T)

当前情节如下:

推荐答案

需要指定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)

只是一个旁注,你可以让你的蒙特卡罗函数更有效率:

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
}

这篇关于在 R 中绘制圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆