I need to plot a circle centered at (0,0) in R. Then I would like to plot points in that circle specified in radius and degrees. Could anyone point me in the right direction for this task?
-
Do you mean radius and degrees?James– James2011-12-12 10:58:44 +00:00Commented Dec 12, 2011 at 10:58
Add a comment
|
3 Answers
In base graphics:
r <- 3*runif(10)
degs <- 360*runif(10)
# First you want to convert the degrees to radians
theta <- 2*pi*degs/360
# Plot your points by converting to cartesian
plot(r*sin(theta),r*cos(theta),xlim=c(-max(r),max(r)),ylim=c(-max(r),max(r)))
# Add a circle around the points
polygon(max(r)*sin(seq(0,2*pi,length.out=100)),max(r)*cos(seq(0,2*pi,length.out=100)))
Note that at least one of the points will be on the border of the circle, so if you dont want this you would have replace of the max(r) statments with something like 1.1*max(r)
1 Comment
Mark Miller
Add
, asp = 1 to the plot statement for the final image to display as a circle instead of an oval.To do this with ggplot2, you need to use coord_polar, ggplot2 will do all the transformations for you. An example in code:
library(ggplot2)
# I use the builtin dataset 'cars'
# Normal points plot
ggplot(aes(x = speed, y = dist), data = cars) + geom_point()

# With polar coordinates
ggplot(aes(x = speed, y = dist), data = cars) + geom_point() +
coord_polar(theta = "dist")

4 Comments
wfbarksdale
Thanks, that looks perfect, but I keep getting
Error in match.arg(theta, c("x", "y")) : 'arg' should be one of “x”, “y”wfbarksdale
the problem with this is that I can't specify location in degrees
Paul Hiemstra
Please post a reproducible example if you want more to the point feedback.
samhiggins2001
That example will work if
coord_polar(theta = "dist") is changed to coord_polar(theta = "y")Use a polar system of coords.(link to wiki).
then transle it into Cartesian coordinate system (link)
and then translate to screen coords ( for example 0,0 is a center of your monitor)