Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How fill part of a circle using ggplot2

Tags:

plot

r

ggplot2

circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){
r = diameter / 2
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))
}
dat <- circleFun(c(1,-1),2.3,npoints = 100)
ggplot(dat,aes(x,y)) + geom_path(color="black") + ggtitle("circle")

I am plotting with ggplot2. I want to fill the circle with blue only in first quadrant. What should I do?

Thank you !

like image 783
Jill Clover Avatar asked Oct 09 '12 07:10

Jill Clover


2 Answers

Is this what you're looking for?

# Define the circle; add a point at the center if the 'pie slice' if the shape is to be filled
circleFun <- function(center=c(0,0), diameter=1, npoints=100, start=0, end=2, filled=TRUE){
  tt <- seq(start*pi, end*pi, length.out=npoints)
  df <- data.frame(
    x = center[1] + diameter / 2 * cos(tt),
    y = center[2] + diameter / 2 * sin(tt)
  )
  if(filled==TRUE) { #add a point at the center so the whole 'pie slice' is filled
    df <- rbind(df, center)
  }
  return(df)
}

#Define separate data frames for the filled and unfilled circle
quarterCircle <- circleFun(c(1,-1), diameter = 2.3, start=0., end=0.5, filled=TRUE)
fullCircle <- circleFun(c(1, -1), 2.3, start=0, end=2, filled=FALSE)

ggplot() + 
  geom_polygon(data=quarterCircle, aes(x,y), color="black", fill="black") + 
  geom_path(data=fullCircle, aes(x, y), color="black") +
  coord_equal()

enter image description here

like image 75
Drew Steen Avatar answered Oct 22 '22 22:10

Drew Steen


Two things:

  1. Use your knowledge of circle geometry and adapt the circle function to start and end at arbitrary points, in this case 0.5*pi and 1.5*pi

  2. Use geom_polygon instead of geom_path

Like this:

circleFun <- function(center=c(0,0), diameter=1, npoints=100, start=0, end=2){
  tt <- seq(start*pi, end*pi, length.out=npoints)
  data.frame(
    x = center[1] + diameter / 2 * cos(tt),
    y = center[2] + diameter / 2 * sin(tt)
  )
}

dat <- circleFun(c(1,-1), 2.3, start=0.5, end=1.5)
ggplot(dat,aes(x,y)) + 
  geom_polygon(color="black") + 
  ggtitle("half circle") +
  coord_equal()

enter image description here

like image 33
Andrie Avatar answered Oct 22 '22 22:10

Andrie