我试图做一个简单的插图,其中圆形被绘制在正方形内.我已经使用了rect()从功能grid包和draw.circle()从功能plotrix包之前,所以我想这将是简单的.但显然我错过了一些东西.
以下代码在我看来它应该工作:
require(plotrix)
require(grid)
plot(c(-1, 1), c(-1,1), type = "n")
rect( -.5, -.5, .5, .5)
draw.circle( 0, 0, .5 )
Run Code Online (Sandbox Code Playgroud)
但是我最终得到的圆圈在垂直方向上从正方形中舔出来,如下所示:

我错过了什么?
如果你有一个简单的方法来绘制圆形和正方形,我很想知道它.但我也想知道为什么我的方法不起作用.
谢谢!
小智 22
您需要指定asp = 1
require(plotrix)
require(grid)
plot(c(-1, 1), c(-1,1), type = "n", asp=1)
rect( -.5, -.5, .5, .5)
draw.circle( 0, 0, .5 )
Run Code Online (Sandbox Code Playgroud)
另请参见:绘制不相交的圆圈 这个也让我受益匪浅!
您可以在TeachingDemos包中使用my.symbols函数:
library(TeachingDemos)
my.symbols(1,1,ms.polygon, n=360, add=FALSE)
my.symbols(1,1, cbind( c(-1,-1,1,1,-1), c(-1,1,1,-1,-1) ), add=TRUE)
Run Code Online (Sandbox Code Playgroud)
这是基础R的解决方案:
x <- seq(-2, 2, 0.01)
y <- seq(-2, 2, 0.01)
plot(x,y, xlim = c(-2,2), ylim=c(-2,2), type='n', asp = 1)
curve(( 1 * (4 - x^2)^0.5 ), add=TRUE, from=-2 , to =2)
curve(( -1 * (4 - x^2)^0.5 ), add=TRUE, from=-2 , to =2)
rect(-2,-2,2,2)
# to fill circle and square
plot(x,y, xlim = c(-2,2), ylim=c(-2,2), type='n', asp = 1)
x2 <- c(seq(-2, 2, 0.01), seq(-2, 2, 0.01))
y2 <- c(( 1 * (4 - x2[1:401]^2)^0.5 ), ( -1 * (4 - x2[402:802]^2)^0.5 ))
rect(-2,-2,2,2, col = 'red')
polygon(x2,y2, col = 'green', border = NA)
Run Code Online (Sandbox Code Playgroud)

编辑
只是为了好玩,这是一个功能:
circle.square.function <- function(radius, x.midpoint, y.midpoint,
my.x.lim, my.y.lim) {
x <- seq(x.midpoint-radius, x.midpoint+radius, 0.01)
y <- seq(y.midpoint-radius, y.midpoint+radius, 0.01)
plot(x,y, xlim = my.x.lim, ylim = my.y.lim, type='n', asp = 1)
curve(( 1 * (radius^2 - (x - x.midpoint)^2)^0.5 + y.midpoint), add=TRUE,
from = (x.midpoint-radius) , to = (x.midpoint+radius))
curve(( -1 * (radius^2 - (x - x.midpoint)^2)^0.5 + y.midpoint), add=TRUE,
from = (x.midpoint-radius) , to = (x.midpoint+radius))
rect((x.midpoint-radius),(y.midpoint-radius),
(x.midpoint+radius),(y.midpoint+radius))
}
radius <- 10 # radius of circle
x.midpoint <- 150 # center of circle on x-axis
y.midpoint <- 50 # center of circle on y-axis
my.x.lim <- c(-100,200) # x-axis to plot
my.y.lim <- c( 0,200) # y-axis to plot
circle.square.function(radius, x.midpoint, y.midpoint, my.x.lim, my.y.lim)
Run Code Online (Sandbox Code Playgroud)