Drawing a series of circles in R

528 Views Asked by At

I made this image in powerpoint to illustrate what I am trying to do:

enter image description here

I am trying to make a series of circles (each of which are the same size) that "move" along the x-axis in consistent intervals; for instance, the center of each consecutive circle would be 2 points away from the previous circle.

I have tried several things, including the DrawCircle function from the DescTools package, but cant produce this. For example, here I am trying to draw 20 circles, where the center of each circle is 2 points away from the previous, and each circle has a radius of 2 (which doesnt work)

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)

How can this be done in R?

3

There are 3 best solutions below

1
dcarlson On BEST ANSWER

This is basically @Peter's answer but with modifications. Your approach was fine but there is no radius= argument in DrawCircle. See the manual page ?DrawCircle for the arguments:

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)

PlotCanvas

But your example has axes:

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)

enter image description here

0
Peter On

Does this do the trick?

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)


I've assumed when you say circle centres are 2 points apart you mean 0.2 units apart.

You may have to experiment with the values to get what you need.

enter image description here

1
Henry Cyranka On

My solution requires the creation of some auxiliary functions

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()

enter image description here