【问题标题】:Drawing a series of circles in R在R中绘制一系列圆圈
【发布时间】:2020-10-29 23:05:54
【问题描述】:

我在 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 中做到这一点?

【问题讨论】:

  • 看看geom_circle from ggforce

标签: r plot geometry desctools


【解决方案1】:

这基本上是@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)

【讨论】:

【解决方案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()

【讨论】:

  • 我接受了 dcarlson 的回答,因为它与我提供的示例直接相关,但我很欣赏 tidyverse 的含义,这是我更喜欢使用的
【解决方案3】:

这能解决问题吗?

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 个单位。

您可能必须尝试使用​​这些值才能获得所需的值。

【讨论】:

    猜你喜欢
    • 2014-04-11
    • 2012-09-19
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多