1

I am looking to create a circle and then overlay a line segment from the origin to a given point on the circle (in this trial run, I chose to have the line segment end at (.25,.25)). For the research I am conducting, I need to be able to generate these line segments in multiple lengths and endpoints, so I am hoping for a code that lends itself to that. Here is what I have thus far. I have only recently started to learn R, so any advice will be well appreciated.

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
  • I think you want `ggplot(circle1,aes(x,y)) + geom_path()` to start with as per the answer that this code originally came from. http://stackoverflow.com/a/6863490/496803 – thelatemail Oct 08 '14 at 04:13
  • I have been able to generate a circle just fine. It's the overlay of line segment(s) that I am having trouble with. Can I do this with geom_path? – Laura Brennan Oct 08 '14 at 04:19
  • Your example code in the question doesn't produce a circle though. I get that you want to create lines from the origin out, but I thought you should at least have the circle to start with. – thelatemail Oct 08 '14 at 04:24
  • `annotate` may be what you want. As in `ggplot(circle1,aes(x,y)) + geom_path() + annotate("segment",x=0,xend=0.25,y=0,yend=0.25)` – thelatemail Oct 08 '14 at 04:27
  • I was trying to manipulate my working circle code to add lines. I can change the code back to the original, which does use `ggplot(circle1,aes(x,y))+geom+plot()` – Laura Brennan Oct 08 '14 at 04:30

1 Answers1

1

The title of your question is ironically close to the answer... use geom_segment.

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

Since you "need to be able to generate these line segments in multiple lengths and endpoints", you should then put the points in a data.frame instead of manually adding them:

# 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))
shadow
  • 21,823
  • 4
  • 63
  • 77