Kozolovska
Kozolovska

Reputation: 1119

Adding unknown multiple lines to ggplot2

How do i add lines using a function to ggplot2? Something in a similar fashion to what i would do in R.

x <- 1:10  ; y <- 1:10

MakeStar <- function(point , numLine , r = 0.5){ 
  for (i in 1:numLine) {
    segments(point[1] , point[2] , point[1] + r * sin(i / (2 * pi)) , point[2] + r * cos(i / (2 * pi)) )
  }
}

plot(y ~ x)
for (j in 1:10) {
  MakeStar(c(x[j],y[j]) , j)
}

enter image description here

To clarify, I'm asking if there's an option in ggplot2 to make a calculation based on some points and then add lines to each of the points similar to the plot above.

Thanks!

Upvotes: 0

Views: 83

Answers (1)

lukeA
lukeA

Reputation: 54237

Imho, your best option to do it "in" ggplot2, is to prepare a data frame beforehand and then plot it. E.g. something in the veins of:

library(ggplot2)
x <- 1:10  ; y <- 1:10
df <- data.frame(x=rep(x, 1:10), y=rep(y, 1:10))
df$i <- ave(1:nrow(df), df$x, df$y, FUN = seq_along)
df$r <- 0.5
p <- ggplot(df, aes(x, y)) + 
  geom_point() 
p + geom_segment(aes(xend=x + r * sin(i / (2 * pi)), yend=y + r * cos(i / (2 * pi)) ))

enter image description here

Upvotes: 2

Related Questions