t.f t.f - 1 year ago 88
R Question

Adding unknown multiple lines to gglot2

How do i add lines using a function to ggplot2?
something in 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 is there an option in ggplot2 , to make a calculation based on some points and then add to each of the point lines similar to the plot above.

Thanks!

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download