2014-10-08 45 views
0

我正在尋找創建一個圓,然後覆蓋從原點到圓上給定點的線段(在此試運行中,我選擇讓線段結束於(.25 ,0.25))。對於我正在進行的研究,我需要能夠以多種長度和端點生成這些線段,所以我希望能夠爲此提供一個代碼。這是我到目前爲止。我最近纔開始學習R,所以任何建議都會很好的讚賞。將線段覆蓋到一個圓上

circle<- function(center=c(0,0),r,npoints=1000){ 
    tt<-seq(0,2*pi,length.out=npoints) 
    xx<-center[1]+r*cos(tt) 
    yy<-center[2]+r*sin(tt) 
    return(data.frame(x=xx,y=yy)) 
} 

circle1<-circle(c(0,0),.48) 
k<-ggplot(circle1,aes(x,y))+geom_line(aes(0,0,.25,.25)) 
k 
+0

我想你根據此代碼最初來自的答案,想要'ggplot(circle1,aes(x,y))+ geom_path()'開始。 http://stackoverflow.com/a/6863490/496803 – thelatemail 2014-10-08 04:13:21

+0

我已經能夠生成一個圓圈就好了。這是我遇到麻煩的線段疊加。我可以用geom_path來做到這一點嗎? – 2014-10-08 04:19:35

+0

雖然您的示例代碼在問題中不會產生圓。我知道你想從源頭創建線條,但我認爲你應該至少有開始的圈子。 – thelatemail 2014-10-08 04:24:37

回答

0

您的問題的標題是諷刺地接近答案...使用geom_segment

ggplot(circle1,aes(x,y)) + geom_path() + 
    geom_segment(x = 0, y=0, xend=0.25, yend=0.25) 

既然你「需要能夠產生多種長度和端點這些線段」,那麼你應該把這些點在data.frame,而不是手動添加:

# dummy data 
df <- data.frame(x.from = 0, y.from=0, x.to=0.25, y.to=c(0.25, 0)) 
# plot 
ggplot(circle1,aes(x,y)) + geom_path() + 
    geom_segment(data=df, aes(x=x.from, y=y.from, xend=x.to, yend=y.to)) 
# depending on how you want to change this plot afterwards, 
# it may make more sense to have the df as the main data instead of the circle 
ggplot(df) + 
    geom_path(data=circle1, aes(x,y)) + 
    geom_segment(aes(x=x.from, y=y.from, xend=x.to, yend=y.to))