如何用ggplot2在水平线上下为圆形填充不同颜色?
在R中绘制分色填充的圆形(按水平线分割)
方法1:使用ggforce包直接绘制分段圆弧
ggforce的geom_arc_bar可以精确绘制圆形的部分区域,完全不需要遮盖操作。首先计算分割线对应的角度:对于半径为1的圆,y=-0.5对应的角度为±150°(或用弧度表示为±5π/6)。
library(ggplot2) library(ggforce) # 计算分割线对应的弧度角度 angle_low <- -5*pi/6 # 等价于210° angle_high <- 5*pi/6 # 等价于150° ggplot() + # 绘制下半部分(y ≤ -0.5),填充红色 geom_arc_bar(aes(x0=0, y0=0, r=1, start=angle_low, end=angle_high, fill="red"), color=NA) + # 绘制上半部分(y ≥ -0.5),填充蓝色 geom_arc_bar(aes(x0=0, y0=0, r=1, start=angle_high, end=angle_low, fill="blue"), color=NA) + scale_fill_identity() + theme_void()
方法2:手动生成多边形顶点(无需额外包)
如果不想依赖第三方包,可以先生成圆的顶点数据,再分割为两个闭合多边形分别填充颜色:
library(ggplot2) # 生成圆的顶点数据,点数量越多边缘越平滑 n_points <- 360 theta <- seq(0, 2*pi, length.out = n_points) circle_df <- data.frame( x = cos(theta), y = sin(theta) ) # 计算分割弦的端点坐标 chord_x <- sqrt(1 - (-0.5)^2) # x=±√3/2≈±0.866 chord_points <- data.frame(x = c(chord_x, -chord_x), y = -0.5) # 构建上半部分多边形(y ≥ -0.5) upper_points <- rbind(subset(circle_df, y >= -0.5), chord_points) # 构建下半部分多边形(y ≤ -0.5),反转端点保证闭合方向正确 lower_points <- rbind(subset(circle_df, y <= -0.5), rev(chord_points)) ggplot() + geom_polygon(data = upper_points, aes(x, y), fill = "blue", color = NA) + geom_polygon(data = lower_points, aes(x, y), fill = "red", color = NA) + theme_void()
说明
- 两种方法都规避了矩形遮盖的弊端,直接绘制目标区域,不会出现边缘瑕疵或覆盖问题。
- 方法1借助
ggforce简化了圆弧绘制逻辑,代码更简洁;方法2用基础ggplot实现,无需额外安装包。
内容的提问来源于stack exchange,提问作者Andrew Swafford
相关产品推荐
相关产品推荐

