如何使用ggplot2填充圆的一部​​分

Joh*_*ass 5 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")
Run Code Online (Sandbox Code Playgroud)

我正在用ggplot2进行策划.我想在第一象限中用蓝色填充圆圈.我该怎么办?

谢谢 !

Dre*_*een 7

这是你在找什么?

# 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


And*_*rie 5

两件事情:

  1. 使用您对圆几何的了解并调整圆函数以在任意点开始和结束,在这种情况下0.5*pi和1.5*pi

  2. 用geom_polygon而不是geom_path

像这样:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @TENGPENG,我认为如果 Andrie 给了你完整的代码,你就会错过*学习*的乐趣。从一点点探索中可以学到很多东西,我认为 Andrie 为您提供了一个很好的起点,可以从这里开始探索。 (2认同)