Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting half circles in R

Tags:

plot

r

geometry

I'm trying to plot half circles using R. My final aim is to draw a circle, divided in the middle by color. The only way I have found yet is to draw two half-circles with different colors.
So I have created my own functions:

upper.half.circle <- function(x,y,r,nsteps=100,...){  
  rs <- seq(0,pi,len=nsteps) 
  xc <- x+r*cos(rs) 
  yc <- y+r*sin(rs) 
  polygon(xc,yc,...) 
} 

lower.half.circle <- function(x,y,r,nsteps=100,...){ 
  rs <- seq(0,pi,len=nsteps) 
  xc <- x-r*cos(rs) 
  yc <- y-r*sin(rs) 
  polygon(xc,yc,...) 
} 

However, for some reason my half-circles end up more like half-ellipses. For example, try running:

plot(1, type="n",axes=F,xlab="", ylab="",xlim=c(0,200),ylim=c(0,200))
upper.half.circle(15,170,10,nsteps=1000,col='red')

Does anyone know why I'm having this trouble, or alternatively, knows of a better way to do what I want?
Thanks!

like image 717
soungalo Avatar asked Jul 21 '15 12:07

soungalo


2 Answers

The problem is the default aspect ratio is not 1:1.

To fix this, set asp=1 in plot:

fixed circle

Inspired by this Q & A. You could have sniffed out this was the case by turning on the axes and x/y labels.

like image 130
MichaelChirico Avatar answered Nov 13 '22 13:11

MichaelChirico


If using the grid package would be also an opportunity for you, there is a much simpler solution:

library(grid)
vp <- viewport(width=0.5, height=0.5, clip  = "on")
grid.circle(0.5,0,r=0.5, gp = gpar(fill = 'red'), vp = vp)

This creates a viewport with clipping, i.e., an appropriate positioning of the filled circle creates a half circle.

like image 4
Patrick Roocks Avatar answered Nov 13 '22 13:11

Patrick Roocks