Plotting half circles in R

2019-06-18 06:48发布

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!

标签: r plot geometry
3条回答
叼着烟拽天下
2楼-- · 2019-06-18 07:20

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.

查看更多
乱世女痞
3楼-- · 2019-06-18 07:20

If you want to add your half circles to an existing plot (and therefore cannot control the aspect ratio directly) then one option for this specific case is to use the floating.pie function from the plotrix package.

A more general tool for creating custom symbols and adding them to plots (with the symbols having a different aspect ratio from the overall plot) is to use the my.symbols function from the TeachingDemos package.

查看更多
Luminary・发光体
4楼-- · 2019-06-18 07:39

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.

查看更多
登录 后发表回答