如何用R绘制带数值标注的半环形图?解决代码问题
R语言实现半环形图(含分段颜色、标线及标签)
需求说明:
- 绘制半环形图,顶部区域85%为深蓝色、15%为浅蓝色
- 在37%位置添加红色标线
- 移除黑线左侧的多余蓝色部分
- 为分段和标线添加对应的百分比文本标签
下面是修改后的完整代码,解决了原代码的问题:
# 清除所有先前对象 rm(list = ls()) library(ggplot2) # 图表模拟数据 data <- data.frame( categorie = c("Categorie 1", "Categorie 2"), waarde = c(0.85, 0.15) ) # 各部分颜色 kleuren <- c("#468bcc", '#cae6f2') # 深蓝和浅蓝 # 标线位置 arrow_pos <- 0.37 # 半环形计算:将数据映射到0~1范围(对应上半环形的0~180度) total <- sum(data$waarde) data$percentage <- data$waarde / total data$start <- cumsum(data$percentage) - data$percentage data$einde <- cumsum(data$percentage) # 创建绘图 plot <- ggplot(data) + # 绘制半环形分段,x范围控制环形宽度,y范围对应0~1(上半环区域) geom_rect(aes(xmin = 1, xmax = 2, ymin = start, ymax = einde, fill = categorie), color = NA) + # 添加红色标线 geom_segment(aes(x = 1, y = arrow_pos, xend = 2, yend = arrow_pos), color = "red", size = 1) + # 设置极坐标,起始角度为pi(180度),仅显示上半环形 coord_polar(theta = "y", start = pi) + # 控制x轴范围,避免显示多余区域 xlim(0.5, 2.5) + theme_void() + theme(legend.position = "none") + # 配置分段颜色 scale_fill_manual(values = kleuren) + # 添加分段百分比标签(显示在环形外侧) geom_text(aes(x = 2.2, y = (start + einde)/2, label = paste0(waarde*100, "%")), size = 4) + # 添加红色标线的百分比标签 geom_text(aes(x = 2.2, y = arrow_pos, label = paste0(arrow_pos*100, "%")), color = "red", size = 4) + # 添加上下边界黑线 geom_segment(aes(x = 1, y = 0, xend = 2, yend = 0), color = "black", size = 1) + geom_segment(aes(x = 1, y = 1, xend = 2, yend = 1), color = "black", size = 1) # 输出图表 print(plot)
关键修改说明:
- 极坐标起始角度调整:将
coord_polar的start参数设为pi,让环形从顶部开始,仅展示0到pi(180度)的上半部分,彻底消除左侧的多余蓝色区域。 - 矩形范围修正:删除原代码中
ymax = einde * 2的错误设置,直接使用einde对应0~1的范围,匹配上半环形的角度区间。 - 文本标签添加:通过
geom_text分别在分段中间位置和标线位置添加百分比标签,x=2.2确保标签显示在环形外侧,清晰可见。 - 图层顺序优化:将边界黑线放在最后添加,避免被环形图形遮挡。
内容的提问来源于stack exchange,提问作者user21699241
相关产品推荐
相关产品推荐

