在R中绘制一系列圆圈

Drawing a series of circles in R

我在 powerpoint 中制作了这张图片来说明我正在尝试做的事情:

我正在尝试制作一系列以一致的间隔沿 x 轴“移动”的圆圈(每个圆圈大小相同);例如,每个连续圆的中心将与前一个圆相距 2 点。

我已经尝试了几种方法,包括 DescTools 包中的 DrawCircle 函数,但无法生成它。例如,这里我想画20个圆,每个圆的圆心与前一个圆的中心相距2个点,每个圆的半径为2(这是行不通的)

library(DescTools)
plotdat <- data.frame(xcords = seq(1,50, by = 2.5), ycords = rep(4,20))
Canvas()
DrawCircle(x=plotdat$xcords, y=plotdat$ycords, radius = 2)

如何在 R 中完成此操作?

这样做有用吗?

library(DescTools)

plotdat <- data.frame(xcords = seq(1, 5, length.out = 20), ycords = rep(4,20))

Canvas(xlim = c(0, 5), xpd=TRUE)

DrawCircle(x=plotdat$xcords, y=plotdat$ycords, r.out = 2)


我假设当你说圆心相距 2 点时,你的意思是相距 0.2 个单位。

您可能需要试验这些值才能获得所需的值。

我的解决方案需要创建一些辅助函数

library(tidyverse)

##First function: create circle with a predefined radius, and a x-shift and y-shift
create_circle <- function(radius,x_shift, y_shift){
    p <- tibble(
        x = radius*cos(seq(0,2*pi, length.out = 1000)) + x_shift ,
        y = radius*sin(seq(0,2*pi, length.out = 1000))+ y_shift
    ) 
    
    return(p)
}

##Use lapply to create circles with multiple x shifts:
##Group is only necessary for plotting
l <- lapply(seq(0,40, by = 2), function(i){
    create_circle(2,i,0) %>%
        mutate(group = i)
})

##Bind rows and plot
bind_rows(l) %>%
    ggplot(aes(x = x, y = y, group =group)) + 
    geom_path()

这基本上是@Peter 的回答,但进行了修改。您的方法很好,但是 DrawCircle 中没有 radius= 参数。有关参数,请参阅手册页 ?DrawCircle

dev.new(width=12, height=4)
Canvas(xlim = c(0,50), ylim=c(2, 6), asp=1, xpd=TRUE)
DrawCircle(x=plotdat$xcords, y=plotdat$ycords, r.out = 2)

但是你的例子有轴:

plot(NA, xlim = c(0,50), ylim=c(2, 6), xlab="", ylab="", yaxt="n", asp=1, xpd=TRUE)
DrawCircle(x=plotdat$xcords, y=plotdat$ycords, r.out = 2)