0

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!

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.