2016-08-22 73 views
0

如何將使用函數的行添加到ggplot2? 東西以類似的方式,以什麼我會盡可能地做將未知的多行添加到ggplot2

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

爲了澄清,我問是否有在GGPLOT2一個選項,以使計算基於一些點,然後添加線與每個類似於上圖的點。

謝謝!

回答

2

Imho,你最好的選擇是在ggplot2中做「事先準備一個數據框,然後繪製它。例如。東西的靜脈:

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