Plot an Archimedean spiral using integer values with ggplot2

2.7k views Asked by At

How do you draw a swirl in R ? I am trying to plot a list of numbers 1:100 and every 7th number assign it a factor '1' all others just '0' . I also have a vector of TRUE or FALSE . How do I plot a swirl of these numbers and highlight every seventh number ? Trying to see if I can tighten or loosen the swirl (theta) to align the 7th numbers. The following code I used to create the data. I used two different functions just to see which vector would work best. A logical vector or a vector of "1" or "0" 's .

returnint  <- function( x ) { 
if ( x == TRUE) {
        return (1)
    } else {
        return (0)
   }  
}

isseven <- function( x ) {
if  (x %% 7)  {
       return (0) # FALSE
    } else {
       return (1) # TRUE
   }
}

fo = seq(1, 100)
fo.sev = NULL # factors
fo.int = NULL   # as int 0 = FALSE , 1 = TRUE

for (i in 1:length(fo)) {
   fo.sev[i] = as.logical(isseven(i)) 
   fo.int[i] = returnint(fo.sev[i])
}


df <- data.frame(fo,fo.int,as.factor(fo.sev))
names(df) <- c("x","intx","seven")
df
2

There are 2 answers

0
Sandipan Dey On

From https://en.wikipedia.org/wiki/Archimedean_spiral, the polar equation of an Archimedian Spiral is r=a+b*theta, with real numbers a and b. The following code can be used to draw one:

# for some fixed real a, b
a <- 2
b <- 3
theta <- seq(0,10*pi,0.01)
r <- a + b*theta
df <- data.frame(x=r*cos(theta), y=r*sin(theta)) # Cartesian coords
library(ggplot2)
ggplot(df, aes(x,y)) + geom_point(col='red')

enter image description here

1
IRTFM On

(I admit to answering the request in the title, but not understanding what the rest of your text was requesting, although I later took a guess.) Just set up data with a pair of parametric equations:

x = t*cos(t); y = t*sin(t)

You need to instantiate t finely enough ... if your purpose is a smooth curve:

 t <- seq(0, 10, by=0.01)
 x = t*cos(t); y = t*sin(t)
 ggplot(data.frame(x,y), aes(x=x,y=y))+geom_path()

enter image description here

This is a guess at what was requested for plotting the integers;

png()
  print( ggplot( df, aes(x=x*cos(x), y=x*sin(x)))  + 
            geom_label(data=df, aes(label=x, color=intx, size=intx + 1) ) + 
            coord_equal() )
  dev.off()

enter image description here

It did appear that the label boxes had a minimum size, since they appeared visible even when their size was zero. And I did get smaller "label boxes" with label.padding = unit(0.05, "lines")